redux 然后工作,但await不工作与Promise从thunk action

8yoxcaq7  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(101)

我正在使用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。如果你知道是什么问题,请帮助。谢谢。

q7solyqu

q7solyqu1#

这里的问题是updatePost不是一个promise,所以即使你调用它的.then也不是“真正”有效的,并且会像你期望的那样工作。
您需要将updatePost更新为这样的promise:

export async function updatePost() {
  try {
    const response = await services.update();
    dispatch(updateFn());
    return response?.data;
  } catch (error) {
    throw error;
  }
}

现在你可以像这样安全地使用它:

await updatePost();
navigation('/page');

相关问题