【问题标题】:Im getting an error with my catch that i cant seem to figure out我的捕获错误,我似乎无法弄清楚
【发布时间】:2020-11-14 21:49:54
【问题描述】:

我对反应还很陌生,但我想我已经开始掌握它的窍门了,就像我认为我遇到了一个我似乎无法弄清楚的问题一样。登录应用程序时,我得到了这个。

Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
(anonymous function)
src/actions/auth.js:105
  102 |       dispatch(push("/app"));
  103 |     })
  104 |     .catch((err) => {
> 105 |       dispatch(authError(err.response.data));
      | ^  106 |     });
  107 | } else {
  108 |   dispatch(authError("Something was wrong. Try again"));

有问题的代码如下。

export function authError(payload) {
  return {
    type: AUTH_FAILURE,
    payload,
  };
}

export function loginUser(creds) {
  return (dispatch) => {
    if (creds.email.length > 0 && creds.password.length > 0) {
      axios
        .post("/auth/login", creds)
        .then((res) => {
          const payload = res.data;
          dispatch(receiveToken(payload));
          dispatch(doInit());
          dispatch(push("/app"));
        })
        .catch((err) => {
          dispatch(authError(err.response.data));
        });
    } else {
      dispatch(authError("Something was wrong. Try again"));
    }
  };
}

问题是服务器响应 "POST /api/auth/login HTTP/1.1" 200 286

所以在这一点上,看起来服务器正在获得正确的信誉,我不知道该怎么办。我正在输入以前有效的正确凭据,无论是否确实发生了错误,它都没有正确捕获它。任何帮助将不胜感激。谢谢

【问题讨论】:

  • 您的错误是告诉您“err”没有“response”属性。你为什么不试试 console.logging “err” 看看它有什么?这可能是一个重要的线索。
  • 我点击链接并尝试了它,仍然没有。我至少得到了 else 语句来抛出一些错误而不是仅仅打破但我直到不知道是什么导致了错误。 autherror() 被触发,但服务器响应 200 代码。

标签: javascript reactjs redux react-redux


【解决方案1】:

console.log(err) 而不是 dispatch(authError(err.response.data)) 首先在你的 catch 块中。然后在chrome中检查,在Console中检查err的结构是什么。

    export function authError(payload) {
  return {
    type: AUTH_FAILURE,
    payload,
  };
}

export function loginUser(creds) {
  return (dispatch) => {
    if (creds.email.length > 0 && creds.password.length > 0) {
      axios
        .post("/auth/login", creds)
        .then((res) => {
          const payload = res.data;
          dispatch(receiveToken(payload));
          dispatch(doInit());
          dispatch(push("/app"));
        })
        .catch((err) => {
          console.log(err);
          //dispatch(authError(err.response.data));
        });
    } else {
      dispatch(authError("Something was wrong. Try again"));
    }
  };
}

【讨论】:

  • 试过了,控制台日志中没有显示错误。这很奇怪,因为我在服务器上收到了 200 个状态码,邮递员可以正常登录。但错误正在被触发。
  • 当您的响应有错误时会发生此问题,例如,当响应正确但在 then 响应中您做了一些引发错误的事情时,axios 然后捕获该错误,即使来自服务器成功。 github.com/axios/axios/issues/1178
  • 这很有意义,我稍后再看看它,看看是什么可能把它搞砸了。在这一点上,这只是一长串 em lol 中的另一个问题。
猜你喜欢
  • 2021-06-04
  • 2011-07-08
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-11
  • 1970-01-01
相关资源
最近更新 更多