javascript - 未捕获( promise )TypeError : Cannot read property 'data' of undefined React/Redux/Axios

标签 javascript axios

当调用有问题的操作(postRequest)时,它返回此数据未定义错误,但是该操作成功并且刷新会清除错误。

错误:

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined:
        payload: err.response.data

前端:

 handleSubmit = event => {
    event.preventDefault();
    this.props.postRequest({ body: this.state.body });
  };
export const postRequest = newRequest => dispatch => {
  dispatch({ type: LOADING_UI });
  axios
    .post('/request', newRequest)
    .then(res => {
      dispatch({
        type: POST_REQUEST,
        payload: res.data
      });
      dispatch(clearErrors());
    })
    .catch(err => {
      dispatch({
        type: SET_ERRORS,
        payload: err.response.data
      });
    });
};

后端:

exports.newRequest = (req, res) => {
  if (req.body.body.trim() === "") {
    return res.status(400).json({ body: "Body must not be empty" });
  }

  db.collection("requests")
    .where("userHandle", "==", req.user.handle)
    .where("status", "==", "awaiting")
    .limit(1)
    .get()
    .then(data => {
      if (!data.empty) {
        return res
          .status(403)
          .json({ general: `Only 1 outstanding request at a time` });
      }
      return db
        .collection("requests")
        .add(newRequest)
        .then(doc => {
          const resRequest = newRequest;
          resRequest.requestId = doc.id;
          res.json({ resRequest });
        });
    })
    .catch(err => {
      res.status(500).json({ error: `sum ting wong` });
      console.error(err);
    });
};

我不明白为什么 - 如果没有捕获错误 - 为什么 err.response.data 有效负载未定义会成为问题。

任何帮助将不胜感激!

更新:根据 Axios 文档更新了前端 w/if 语句,但是现在不会抛出任何错误,它只是继续加载,仍然会执行操作并刷新修复。

 .catch(err => {
      if (err.response) {
            dispatch({
          type: SET_ERRORS,
          payload: err.response.data
        });
          }
    });

最佳答案

它会抛出错误,因为您需要在访问数据属性之前JSON.parse()响应。

axios
    .post('/request', newRequest)
    // add this
    .then(resp => JSON.parse(resp))
    .then(res => {
      dispatch({
        type: POST_REQUEST,
        payload: res.data
      });
      dispatch(clearErrors());
    })
    .catch(err => {
      dispatch({
        type: SET_ERRORS,
        payload: err.response.data
      });
    });

如果不解析 JSON,您的代码将无法访问数据属性,因此会引发错误。

一旦抛出,错误对象上就没有响应属性。 删除该行,添加一个 console.log,您将看到它抛出错误。

关于javascript - 未捕获( promise )TypeError : Cannot read property 'data' of undefined React/Redux/Axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57814681/

相关文章:

javascript - React 无法在 axios 之外分配类字段

javascript - 使用express配置CORS并使用axios在前端发出请求

javascript - URL 中的回调是什么

javascript - 解析 JSON 以排除重复 Node.JS

javascript - 如何生成带有样式的PDF并将其上传到服务器(Jquery)

javascript - 合并两个对象数组并跳过具有相同 ID 属性的对象

node.js - Axios 请求带有来自 Node 的分块响应流

javascript - axios响应错误: certificate has expired

node.js - ReactJS + Axios + NodeJS - _id : Cannot read property 'ownerDocument' of null

javascript - 单击按钮时如何在同一页面中显示表单