【问题标题】:Possible unhandled promise rejection while catch is present存在捕获时可能未处理的承诺拒绝
【发布时间】:2018-08-12 03:30:54
【问题描述】:

我有以下代码:

export function fetchValueFromApi(){
    return function act(dispatch){
        dispatch(fetchingLimit);
        return fetch('https://someapi/v1/foo/bar?api_key=123456789')
          .then(response =>{
              console.log("response",response.json());
              response.json();
          }).then(json =>{
              if (json.data()) {
                  dispatch(receivingValue(json.data.result))
              } else {
                  throw new Error('Error');
              }
          }).catch(error => dispatch(receivingValueFailed(error)))
    }
}

现在我知道这个调用不会成功。我期待它失败并陷入困境。但是,我收到此错误:

可能的未处理承诺拒绝

所以由于某种原因,我们没有点击.catch

我该如何解决这个问题?

【问题讨论】:

  • 嗯,你的 catch 处理程序也会抛出错误吗?
  • 当我将它添加到捕获 console.log('Catching the error', error); 时,它会打印:TypeError: Cannot read property 'data' of undefined。但实际上我知道端点会抛出 403
  • 哦,我认为无论http状态如何,fetch都会返回成功。
  • 顺便说一句,您在response.json()之前错过了一个回报

标签: javascript react-native redux promise


【解决方案1】:

您不是 return 来自您的 then 处理程序的承诺,因此没有链接。甚至没有等待响应正文。 catch 处理程序未链接到实际拒绝的承诺,因此错误确实未处理。

export function fetchValueFromApi(){
    return function act(dispatch){
        dispatch(fetchingLimit);
        return fetch('https://someapi/v1/foo/bar?api_key=123456789')
        .then(response => {
            var body = response.json();
            console.log("response body", body);
            return body;
//          ^^^^^^
        }).then(json => {
            if (json.data ) {
//                       ^
                return dispatch(receivingValue(json.data.result))
//              ^^^^^^
              } else {
                  throw new Error('Error');
              }
          }).catch(error =>
              dispatch(receivingValueFailed(error))
          )
     }
}

请记住,箭头函数仅在您使用简洁的正文语法时隐式返回表达式值,即没有大括号。

【讨论】:

    【解决方案2】:

    所以你正在抓住问题,只是没有出现你预期的错误。

    就 fetch 而言,403 不是错误,因为请求本身已成功发出(响应不是您的应用程序所期望的)。您必须自己处理 40X 错误。正如您的 console.log 显示的那样,异常发生在您的 throw new Error 到达之前。

    当网络错误发生时,一个 fetch() 承诺将拒绝一个 TypeError 在服务器端遇到或 CORS 配置错误,尽管这 通常意味着权限问题或类似问题——404 不构成 例如网络错误。

    来自https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    你应该

    1. 在第一个 .then 处理程序中返回 response.json().then(response => response.ok && response.json())
    2. 在第二个 .then 处理程序中添加更安全的检查,例如 if (json && json.data)
    3. 如果没有 json 数据,则调度失败操作而不是抛出错误

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 1970-01-01
      • 2015-10-06
      • 2016-12-15
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多