【问题标题】:Axios Unhandled Promise RejectionAxios 未处理的承诺拒绝
【发布时间】:2018-11-01 07:24:44
【问题描述】:

我在我的 react-native 应用程序中遇到了 axios 问题。 此处提供错误消息Pic1Pic2 Actions.start() 永远不会运行。

编辑 1: 这是完整的代码。 编辑2: 错误信息图片Pic3 至于结果, const res= await... 应该是问题所在。 必须添加更多细节,否则我无法更新这个问题;)

export const apiPostLogin = (
 accountData
) => async dispatch => {
dispatch(setFetching(true));
try {
  var instance = axios.create({
    baseURL: 'https://api.xxxx.de/',
    timeout: 1000
 });

const res = await axios.post('/api/v1/auth/login', accountData);
Actions.Start();

dispatch(setAuthToken(res.data.token));


  await dispatch(apiGetAccount(res.data.token));
  console.log(res);
} catch (error) {
  console.log(error.response);
  dispatch(setFetching(false));
  if (error.response.status === 401) {
  dispatch(
    setApiResponse({
      apiResponse: true,
      didShowResponse: false,
      apiResponseError: true,
      apiResponseCode: 401,
      apiResponseMessage: 'E-Mail und Passwort stimmen nicht überein'
    })
  );
} else if (error.response.status === 417) {
  dispatch(
    setApiResponse({
      apiResponse: true,
      didShowResponse: false,
      apiResponseError: true,
      apiResponseCode: 417,
      apiResponseMessage: 'Du hast Deine E-Mail noch nicht bestätigt'
    })
  );
} else {
  dispatch(
    setApiResponse({
      apiResponse: true,
      didShowResponse: false,
      apiResponseError: true,
      apiResponseCode: 499,
      apiResponseMessage:
        'Du kannst Dich im Moment nicht bei uns anmelden. Wir befinden   uns im Wartungsmodus'
    })
   );
   }
  }
  };

【问题讨论】:

    标签: react-native react-redux axios


    【解决方案1】:

    post 调用包装在try catch(catch 对于处理被拒绝的promise)块中。您的网络请求失败。您需要捕获错误/处理承诺拒绝

        try {
            const res = await axios.post('/api/v1/auth/login', accountData);
            console.log('Success!');
            console.log(res.status);
            console.log(res.data);
        } catch (e) {
            console.error('Failure!');
            console.error(e.response.status);
            throw new Error(e);
        }
        Actions.Start();
    

    或 尝试使用axios() 而不是axios.create()

    return axios.({
        method: 'post',
        baseURL: userEndpoint,
        headers: {
            common: {
                Accept: 'application/json',
            }
        }
    }).then(...).catch(...);
    

    【讨论】:

    • 您好,谢谢您的回答!但它仍然不起作用。整个块也包含在 Try{} catch 语句中。您还有其他想法吗?
    • 是的,等一下
    • console.log(error.response); 是否在 catch 块中执行?
    • 我也尝试使用 fetch by react native。我得到了同样的错误。我的模拟安卓设备有什么问题吗?
    • 感谢您的评论,这让我大开眼界,您可能面临与我相同的问题,即使用localhost 作为 api url,但我不能这样做,因为模拟设备不是在与服务器相同的主机上,所以我需要使用192.168.0.1 或类似的东西:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2023-03-17
    • 2018-04-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多