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
相关产品推荐
相关产品推荐

