javascript - 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
进入,并在第二次渲染时被绕过。finally
finally
剂量任何人都有相同的经历或可以向我解释发生了什么......
我真的很感激。
解决方案
尝试finally
正确编写回调,即
() => {
setIsFetching(false);
console.log('finally');
}
正如所写的那样,两行都被执行,但是 console.log 立即执行并且不包含在回调中。这是一个以逗号分隔的表达式列表,所有表达式都被评估并返回最后一个。
finally 块回调问题的示例
(setTimeout(() => console.log('hi'), 2000), console.log('test'))
逗号运算符( ) 计算其
,
每个操作数(从左到右)并返回最后一个操作数的值。这使您可以创建一个复合表达式,在其中计算多个表达式,复合表达式的最终值是其最右边的成员表达式的值。
推荐阅读
- c++ - std::thread 构造函数?专业化?。g++与clang++
- c++ - OpenGL - 在 ubuntu 的线程上创建 vbo?
- c# - 使用 Identity Core 的 ASP.NET MVC 框架中的标识
- javascript - 如何使用 if else 语句在 javascript 对象中创建键
- c# - 附加到游戏对象时,粒子系统粉红色
- react-native - 如何在本机反应中访问导航选项中的组件状态?
- android - 使用 RecyclerView 中的自定义 ListUpdateCallback 和 PagedList
- css - 滚动条未显示在平板电脑上
- javascript - NodeJS在模块中的一些混合
- jquery - 检查多个输入值是否不为空