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 绕过了thencatch,并在第一次渲染时直接进入finally,并在第二次渲染时绕过finally

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

我真的很感激。

尝试正确编写finally回调,即

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

如前所述,两行都执行,但控制台.log立即执行,并且不包含在回调中。它是一个逗号描述的表达式列表,所有表达式都得到计算,最后一个被返回。

最终阻止回调问题示例

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

逗号运算符

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

你在 finally 块中写错了 cod,请使用以下更改

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');});
};

最新更新