无法捕获 axios React.js 中的错误

我正在reactjs项目中使用axios进行API调用,但不知何故我无法捕获错误。我收到404但无法捕获它。有人可以告诉我出了什么问题吗?


abc.js


export default axios.create({

  baseURL: `my_base_url`,

  headers: {

    "Content-Type": "application/json",

  },

});

xyz.js


export const createProcessApiCall = (param) => {

  return API.post("/v1/process1", param);

};

zzz.js


  const postData = async (param) => {

    await createProcessApiCall(param)

      .then((response) => {

          setApiData(response.data.data);

          setIsSuccess(response.data.isSuccess);    

      })

      .catch((e) => {

        setIsError(true);

      });

  };


牛魔王的故事
浏览 92回答 3
3回答

慕桂英3389331

您正在将异步代码与同步代码相结合,请尝试使用 asyncchron :   const postData = async (param) => {    try {       const result = await createProcessApiCall(param)    }    catch(err) {         setIsError(true);     }       };或者同步:const postData = (param) => {    createProcessApiCall(param)      .then((response) => {          setApiData(response.data.data);          setIsSuccess(response.data.isSuccess);          })      .catch((e) => {        setIsError(true);      });  };

拉莫斯之舞

axios.interceptors.response.use(res=>{return res}, (error) => { if (error.response.status !== 401) {   throw error;}if (typeof error.response.data.error.name !== "undefined") {   //do something on the error}});最好使用 axios 拦截器来捕获错误

忽然笑

任何与 200-299 之间包含的序列不同的状态代码,您都需要捕获:  const postData = async (param) => {    await createProcessApiCall(param)      .then((response) => {          setApiData(response.data.data);          setIsSuccess(response.data.isSuccess);          })      .catch((e) => {        // @TODO parse err        console.log(e.response);        setIsError(true);      });  };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript