这些错误是 Axios API 调用的结果吗?

Are these errors a result of the Axios API call?

我正在开发后端 API,调用 API 的 React 前端随机获得 Network ErrorCannot read properties of undefined (reading 'data')。我无法重现此行为。它被报告在前端的日志中,但它没有出现在后端的日志中,据我所知,请求甚至没有达到 API。前端正在使用 Axios 进行 API 调用。下面是出现这些错误的两个调用的示例。此代码中的任何内容可能会导致这些错误?

const params = `email=${this.queryParams.email}`;

const response = await axiosStore.axiosApi.get(`/data?${params}`).catch(error => {
    console.error(error);
});
const values = await response.data;

this.setValues(values);
const response = await axiosStore.axiosApi.post(`/data`, { data: mappedChanges }).catch(error => {
    if (error && error.response && error.response.data && error.response.data.errors) {
        const { errors } = error.response.data;
        const message = Object.keys(errors)
            .map(x => errors[x])
            .join(', ');
        throw new Error(message);
    } else {
        throw new Error('Something went wrong');
    }
});
newObject = response.data;

好吧,我猜是因为您混合使用 await 和 catch 可能会使错误追加。如果您的调用有误。你抓住它然后响应对象可能是未定义的。 然后,当您尝试从响应中获取数据时,您将收到此错误。 而且我不确定您是否需要在 response.data 上调用 await。你确定这是一个承诺? 如果我是你,我会将调用包装到 try catch 中,以便更容易调试


const getStuff1 = async () => {
  const params = `email=${this.queryParams.email}`;
  try {
    const response = await axiosStore.axiosApi.get(`/data? ${params}`);
    const values = response.data;
    this.setValues(values);
  } catch(error) {
    console.error(error);
  }    
};

const getStuff2 = async () => {
  try {
    const response = await axiosStore.axiosApi.post(`/data`,
     { data: mappedChanges }
    );
    newObject = response.data;
  } catch(error) {
    if (error?.response?.data?.errors) {
      const { errors } = error.response.data;
      const message = Object.keys(errors)
            .map(x => errors[x])
            .join(', ');
        // Do something with error
    } else {
        // Do something with error
    }
  }

};