【问题标题】:Axios - Unhandled Rejection (TypeError): Cannot read property 'data' of undefinedAxios - 未处理的拒绝(TypeError):无法读取未定义的属性“数据”
【发布时间】:2021-08-16 10:46:26
【问题描述】:

我试图自己找出问题所在,但试图找出问题的 a$$ 一直很痛苦。我正在使用 axios 并且不知道似乎是什么导致了问题。 (我是 ReactJS 的新手)下面我发布了一个屏幕截图,如果它会让您更容易确定问题。 enter image description here

export const actFetchMealsRequest = () => {
    return (dispatch) => {
        return callApi('/Product', 'GET', null).then(res => {
            dispatch(GetAllMeal(res.data));
        });
    }
}

/*GET_ALL_MEAL*/
export function GetAllMeal(payload){
    return{
        type:'GET_ALL_MEAL',
        payload
    }
}

【问题讨论】:

  • 它说你 res 是 undefined 。而你正在尝试做 undefined.data 。你能添加你的callApi的代码吗?
  • 我能够在callApi中解决问题,谢谢。 :)

标签: reactjs typeerror


【解决方案1】:

按照@Shyam 的建议,我已经解决了我的 callApi 中的问题, 这是我之前的代码:

import axios from 'axios';
let API_URL = 'https://5adc8779b80f490014fb883a.mockapi.io';
   export default function callApi(endpoint, method = 'GET', body) {
       return axios({
           method,
           url: `${API_URL}/${endpoint}`,
           data: body
       }).catch(err => {
           console.log(err);
       });
}

这是更新后的代码:

import axios from 'axios';
let API_URL = 'https://5adc8779b80f490014fb883a.mockapi.io';
   export default async function callApi(endpoint, method = 'GET', body) {
       try {
           return axios({
               method,
               url: `${API_URL}/${endpoint}`,
               data: body
           });
       } catch (err) {
           console.log(err);
       }
}

我刚刚转换为异步函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2020-06-01
    • 2021-10-06
    • 2019-07-19
    • 2019-06-03
    • 2020-04-09
    相关资源
    最近更新 更多