从中间件调度 thunk 会导致错误
Dispatching a thunk from a middleware results in an error
我的 actions.js
文件中定义了一个 thunk:
export const myThunk = (param1, param2, param3) => {
return dispatch => {
dispatch({type: types.myThunkType})
fetch(`https://mockurl.com?param1=${param1}¶m2=${param2}¶m3=${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 |
因为它不能“return 下一个动作”。关于我做错了什么的任何提示?
编辑:在调试中检查,我发现调度的 thunk 在到达中间件时看起来像这样:https://imgur.com/s7AS8eD
我的 actions.js
文件中定义了一个 thunk:
export const myThunk = (param1, param2, param3) => {
return dispatch => {
dispatch({type: types.myThunkType})
fetch(`https://mockurl.com?param1=${param1}¶m2=${param2}¶m3=${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 |
因为它不能“return 下一个动作”。关于我做错了什么的任何提示?
编辑:在调试中检查,我发现调度的 thunk 在到达中间件时看起来像这样:https://imgur.com/s7AS8eD