首页 > 解决方案 > Axios 似乎直接绕过了 .then/.catch 和触发了 .finally

问题描述

我正在使用 React(16.13.1) 和 Axios(0.19.0) 并遇到一个奇怪的情况......

多个console.log()被设置为试图找出问题。

  const signUserAPI = async (data) => {
    console.log('top of the function')
    await setIsFetching(true);
    await setIsError('');

    axios.post(
      apiPath.signUpPath,
      { user: data },
    ).then((response) =>{
      console.log('then')
      console.log(response)
      setIsSuccess(true)
      }   
    ).catch((e) => {
      console.log('catch')
      setIsSuccess(false);
      setIsError(e);

      if (e.response) {
          ...
      }

    }).finally(() => setIsFetching(false), console.log('finally'));
  };

axios.post被解雇时,我应该按以下顺序使用 console.log() 获取内容

// in console

'top of the function'
'then'
'response content...'
'finally'

// OR

'top of the function'
'catch'
'finally'

但我真正得到的是

// at 1st render
'top of the function' 
'finally'

// at 2nd render
'then'
'response content ...' 

// OR

// at 1st render
'top of the function'
'finally'

// at 2nd render
'catch'

看起来 axios 在第一次渲染时绕过then或直接catch进入,并在第二次渲染时被绕过。finallyfinally

剂量任何人都有相同的经历或可以向我解释发生了什么......

我真的很感激。

标签: javascriptreactjsaxios

解决方案


尝试finally正确编写回调,即

() => {
  setIsFetching(false);
  console.log('finally');
}

正如所写的那样,两行都被执行,但是 console.log 立即执行并且不包含在回调中。这是一个以逗号分隔的表达式列表,所有表达式都被评估并返回最后一个。

finally 块回调问题的示例

(setTimeout(() => console.log('hi'), 2000), console.log('test'))

逗号运算符

逗号运算符( ) 计算其,每个操作数(从左到右)并返回最后一个操作数的值。这使您可以创建一个复合表达式,在其中计算多个表达式,复合表达式的最终值是其最右边的成员表达式的值。


推荐阅读