我正在使用redux/toolkit,并有一个thunk动作来请求更新API然后进行导航。
我尝试返回一个promise,以便在导航之前等待操作完成。
API调用后开始出现问题。如果我使用then
,Promise会正常工作,当我之后导航时不会有任何问题。
但是当我将它与await dispatch(updatePost())
一起使用时,我开始收到内存泄漏警告,并怀疑Promise可能在导航之前没有解决。我尝试设置TimeOut导航为5秒,然后没有任何警告。无论API调用是否成功,都会出现问题。
// Thunk action trying to return a Promise
export function updatePost() {
return () =>
services
.update()
.then((response: any) => {
dispatch(updateFn())
return response?.data
})
.catch((error: any) => {
throw error
});
}
// This works fine
updatePost().then(() => {
navigation('/page');
})
// This cause memory leak warnings
await updatePost();
navigation('/page');
我需要使用await
的原因是我有更多的函数可以使用Promise。如果你知道是什么问题,请帮助。谢谢。
1条答案
按热度按时间q7solyqu1#
这里的问题是
updatePost
不是一个promise,所以即使你调用它的.then
也不是“真正”有效的,并且会像你期望的那样工作。您需要将
updatePost
更新为这样的promise:现在你可以像这样安全地使用它: