亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法捕獲 axios React.js 中的錯誤

無法捕獲 axios React.js 中的錯誤

牛魔王的故事 2024-01-18 16:04:57
我正在reactjs項目中使用axios進行API調用,但不知何故我無法捕獲錯誤。我收到404但無法捕獲它。有人可以告訴我出了什么問題嗎?abc.jsexport default axios.create({  baseURL: `my_base_url`,  headers: {    "Content-Type": "application/json",  },});xyz.jsexport 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);      });  };
查看完整描述

3 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

您正在將異步代碼與同步代碼相結合,請嘗試使用 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);

      });

  };


查看完整回答
反對 回復 2024-01-18
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

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 攔截器來捕獲錯誤


查看完整回答
反對 回復 2024-01-18
?
忽然笑

TA貢獻1806條經驗 獲得超5個贊

任何與 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);

      });

  };


查看完整回答
反對 回復 2024-01-18
  • 3 回答
  • 0 關注
  • 244 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號