反应本机获取不调用然后或捕获



我正在使用 fetch 在 react-native 中进行一些 API 调用,有时随机 fetch 不会触发对服务器的请求,并且不会调用我的 then 或 except 块。这是随机发生的,我认为可能存在竞争条件或类似的东西。在像这样一次请求失败后,对同一 API 的请求永远不会被触发,直到我重新加载应用程序。任何想法如何追踪这背后的原因。我使用的代码如下。

const host = liveBaseHost;
const url = `${host}${route}?observer_id=${user._id}`;
let options = Object.assign({
        method: verb
    }, params
    ? {
        body: JSON.stringify(params)
    }
    : null);
options.headers = NimbusApi.headers(user)
return fetch(url, options).then(resp => {
    let json = resp.json();
    if (resp.ok) {
        return json
    }
    return json.then(err => {
        throw err
    });
}).then(json => json);

Fetch 可能抛出错误,并且您尚未添加 catch 块。试试这个:

return fetch(url, options)
  .then((resp) => {
    if (resp.ok) {
      return resp.json()
        .then((responseData) => {
          return responseData;
        });
    }
    return resp.json()
      .then((error) => {
        return Promise.reject(error);
      });
  })
  .catch(err => {/* catch the error here */});

请记住,承诺通常具有以下格式:

promise(params)
  .then(resp => { /* This callback is called is promise is resolved */ },
        cause => {/* This callback is called if primise is rejected */})
  .catch(error => { /* This callback is called if an unmanaged error is thrown */ });

我以这种方式使用它,因为我以前遇到过同样的问题。

让我知道它是否对您有帮助。

fetch包裹在 try-catch 中:

let res;
try {
    res = fetch();
} catch(err) {
    console.error('err.message:', err.message);
}

如果您看到"网络故障错误",它要么是 CORS 要么是真正有趣的错误,但它让我过去,请检查您是否未处于飞行模式。

我也陷入了困境,api 调用既不会进入,也不会进入捕获。确保您的手机和开发代码连接到相同的互联网网络,这对我来说很有效。

相关内容

最新更新