为了账号安全,请及时绑定邮箱和手机立即绑定

从中间件调度 thunk 会导致错误

从中间件调度 thunk 会导致错误

茅侃侃 2023-04-27 16:26:23
我的actions.js文件中定义了一个 thunk:export const myThunk = (param1, param2, param3) => {   return dispatch => {      dispatch({type: types.myThunkType})      fetch(`https://mockurl.com?param1=${param1}&param2=${param2}&param3=${param3}`)      .then(response => response.json())      .then(data => {         dispatch({type: types.everythingsAllRight, payload: data.results})      })   }}当我从 React 组件分派它时,一切都像魅力一样。在我的component.js我们有这样的东西:import myThunk from './actions/actions.js'const dispatch = useDispatch()return (   <button onClick={() => {dispatch(myThunk(props.param1, props.param2, props.param3)}>)但是当我尝试从中间件使用相同的 thunk 时,如下所示:   store.dispatch(anPlainObjectActionDefinedInActionsJsToo(param1, param2, false))   .then(() => {       store.dispatch({         type: types.anotherImportantActionType,         payload: {            thisData: someData,            thatData: someOtherData         }      })   })   .then(store.dispatch(myThunk(param1, param2, param3)))我收到此错误:Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.错误是命中处理动作类型的中间件myThunkType:Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.▶ 3 stack frames were collapsed.(anonymous function)src/Store/middleware/middlewareThatDealsWithMyThunkTupeActionType.js:9   6 | }   7 | if (action.type !== types.myThunkType &&   8 |    action.type !== types.anotherType) {>  9 |    return next(action)     | ^  10 | }  11 | 因为它不能“返回下一个动作”。有什么迹象表明我做错了吗?编辑:在调试中检查,我发现发送的 thunk 在遇到中间件时看起来像这样:https: //imgur.com/s7AS8eD
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

您需要将一个函数传递给您.then,但不像现在那样立即调用它。此外,更改您的中间件以使用柯里化来传递分派并创建闭包。将最后一个then块重写为

.then(() => {
store.dispatch(myThunk(param1, param2, param3))
})


查看完整回答
反对 回复 2023-04-27
  • 1 回答
  • 0 关注
  • 84 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信