You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中派发Async异步action时如何返回空action规避报错

问题原因

Redux 要求所有通过 dispatch 派发的内容必须符合以下两种规范之一:

  • 合法的标准action对象,至少包含type字段
  • 被Redux Thunk中间件处理的异步函数

当前你的updateRestoreProgress action创建函数在条件不成立时没有任何返回值,dispatch 接收到undefined后会尝试读取它的type属性,因此抛出对应报错。

可行解决方案

方案1:action创建函数兜底返回空action

在条件判断不成立的分支,返回一个无副作用的空action即可,reducer不需要对这个action做额外处理,收到后直接返回原有state即可。
修改后的action.js代码:

# action.js

export const updateRestoreProgress = ( isAuthenticated, restoringProgressCompleted, mail, currentlyRestoringCount) => {

  if (isAuthenticated && !restoringProgressCompleted) {
     return async (dispatch) => {
        // ... async calls
        // ... dispatch(methods)
        // ...
     }
  }
  // 兜底返回空action,type值只要不与现有业务type重复即可
  return {
    type: 'UPDATE_RESTORE_PROGRESS_NO_OP'
  }
}

方案2:派发前先做条件判断

在组件调用dispatch之前先校验条件,只有符合条件时才派发action,不需要修改action创建函数的逻辑。
修改后的landingScreen.js代码:

#landingScreen.js

useEffect(() => {
  // 先判断条件再派发
  if (isAuthenticated && !restoringProgressCompleted) {
    dispatch(updateRestoreProgress(isAuthenticated, restoringProgressCompleted, mail, currentlyRestoringCount));
  }
}, [isAuthenticated, restoringProgressCompleted]);

注意这里需要把restoringProgressCompleted加到useEffect的依赖数组中,保证依赖项完整,避免闭包问题。


内容的提问来源于stack exchange,提问作者ahkam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:33:00