从中间件分派thunk会导致错误

问题描述

我在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)}>
)

但是当我尝试从中间件中使用相同的重击时,就像这样:

   store.dispatch(anPlainObjectActionDefinedInActionsJsToo(param1,false))
   .then(() => { 
      store.dispatch({
         type: types.anotherImportantActionType,payload: {
            thisData: someData,thatData: someOtherData
         }
      })
   })
   .then(store.dispatch(myThunk(param1,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

解决方法

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

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

您可以详细了解自定义redux中间件和使用here