【问题标题】:Unhandled Rejection (TypeError): Cannot read property 'statusText' of undefined未处理的拒绝(TypeError):无法读取未定义的属性“statusText”
【发布时间】:2020-04-09 19:58:01
【问题描述】:

我在尝试使用 react-redux 实现删除功能时遇到了这个问题。

action/profile.js

export const deleteExperience = id => async dispatch => {
  try {
    const res = await axios.delete(`/api/profile/experience/${id}`);

    dispatch({
      type: UPDATE_PROFILE,
      payload: res.data
    });

    dispatch(setAlert("Experience Removed", "success"));
  } catch (err) {
    dispatch({
      type: PROFILE_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status }
    });
  }
};

reducers/profile.js

case UPDATE_PROFILE:
  return {
    ...state,
    profile: payload,
    loading: false
  };
case PROFILE_ERROR:
  return {
    ...state,
    error: payload,
    loading: false
  };

【问题讨论】:

  • 但是如果Cannot read property 'statusText' of undefined 在catch 内,你会在哪一行得到Cannot read property 'statusText' of undefined - 首先尝试console.log err.response 并查看存在哪些属性
  • @Zydnar 我试图 console.log err.response 但我什么也没得到。实际上,删除工作正常,正在从数据库中删除条目。但不是显示成功警告 catch 块代码正在运行
  • 如果删除有效,这意味着运行了 try 块,但这并不意味着错误是 somwere else Cannot read property 'statusText' of undefined 这意味着 err.response 未定义 - 也许您遇到了错误类型的错误。将 catch 块的内容包装在 if(err.response){ 中,否则为 console.error(err)
  • 您可以尝试暂时删除此行dispatch(setAlert('Experience Removed', 'success')) 吗?如果可行,您可以在问题中添加 setAlert 代码吗?

标签: javascript react-redux


【解决方案1】:

问题出在删除 API 中。 API 应该像 http://localhost:5000/api/profile/experience/5df8f54012b7a81ac04d6b25 这样工作,但不知何故,它也以这种方式工作,http://localhost:5000/api/profile/experience/5d 使用用户的令牌。所以我从

更改了api代码
try {
    const profile = await Profile.findOne({ user: req.user.id })
    const removeIndex = profile.education.map(item => item.id).indexOf(req.params.edu_id)
    profile.education.splice(removeIndex, 1)

    await profile.save()
    res.json({ msg: 'Education Deleted'})
} catch (err) {
    console.log(err.message)
    res.status(500).send('Server Error')
}

try {
    const foundProfile = await Profile.findOne({ user: req.user.id });
    const eduIds = foundProfile.education.map(edu => edu._id.toString());
    const removeIndex = eduIds.indexOf(req.params.edu_id);
    if (removeIndex === -1) {
        return res.status(500).json({ msg: "Server error" });
    } else { 
        foundProfile.education.splice(removeIndex,1);
        await foundProfile.save();
        res.json({ msg: 'Education Deleted'})
    }
} catch (error) {
    console.error(error);
    return res.status(500).json({ msg: "Server error" });
}

现在一切正常。

【讨论】:

    猜你喜欢
    • 2019-04-07
    • 2019-07-19
    • 2019-06-03
    • 2019-11-13
    • 2021-10-19
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多