首页 > 解决方案 > React Native、Axios 和未处理的 Promise Rejections

问题描述

我在我的 React-Native 应用程序中使用 Axios 与 Nodejs 后端通信,并使用 react-redux 调度来调用将利用 Axios 的操作。但是,无论我尝试什么,只要出现任何类型的错误,我都会得到“未处理的承诺拒绝”。这让我非常沮丧,我即将放弃 Axios 并重新使用 fetch。我已经用谷歌搜索了这个问题(这似乎确实很常见),但还没有找到任何可靠的解决方案。

这是我如何在操作中使用 Axios 向我的 Nodejs 后端服务器发送请求的示例:

    export const getAppointments = (userId) => {
  return async (dispatch) => {
      const request = axios
        .get(`${SERVER_BOOKINGS}/upcoming_appointments/${userId}`)
        .then((response) => {
          let ourPayload = {};
          ourPayload.success = response.data.success;
          if (ourPayload.success) {
            ourPayload.bookings = response.data.bookings;
            dispatch({
              type: GET_UPCOMING_APPOINTMENTS,
              payload: ourPayload,
            });
          } 
        })
        .catch((err) => {
          console.log("caught an error, HERE:", err);             
          //throw err
        });   
  };
};

这是我用来调用此操作的代码:

 const getAppointments = async () => {
    try {
      await dispatch(
        bookingActions.getAppointments(userObject.userData.userId)
      );
    } catch (error) {
      console.log("we actually caught an axios error client side!");
    }
  }

如果我完全按照上面的方式保留代码,并且故意从我的 Nodejs 代码中引起错误响应,我会收到一条 console.log 消息,上面写着“在此处捕获错误”,但从我实际调度操作的 catch 块中什么也得不到(第二块代码)。

如果我取消注释第一个 catch 块中的 throw err 行,我仍然会得到 console.log,仍然没有从第二个 catch 块中得到任何东西......但现在我收到了 Unhandled Promise Rejection 警告。

现在,只要没有错误,这段代码就可以很好地工作,并且只要有错误就完全没有价值。老实说,我不知道问题是与 axios、react-redux 调度有关还是只是我未能理解 Promise 的工作方式,但我已经浪费了无数时间试图弄清楚是什么捕捉错误应该是一件非常简单的事情......因此我在这个项目上落后于计划。任何建议/帮助将不胜感激!

标签: javascriptreact-nativeaxios

解决方案


我认为问题是由于“bookingActions.getAppointments”不是 Promise 函数造成的,因此无需“try-catch”它。尝试像这样更改它:

const getAppointments = () => dispatch(bookingActions.getAppointments(userObject.userData.userId));

推荐阅读