如何修复React-Redux报错Actions must be plain objects异步action问题
React-Redux报错「Actions must be plain objects. Use custom middleware for async actions」解决方案
报错原因
你定义的listProducts是异步thunk函数,调用后返回的是函数而非普通action对象,默认Redux仅支持分发普通对象类型的action,需要通过redux-thunk中间件处理异步action的分发逻辑。
你已经引入了redux-thunk依赖,但配置Store时没有将thunk中间件注册到Redux中,导致中间件未生效,无法识别函数类型的action。
查看你的Store代码可以发现问题:
// 你定义了包含thunk的中间件数组,但后续没有传入使用 const middleware = [thunk]; const store = createStore( reducer, initialState, // 这里applyMiddleware没有传入任何中间件,等于没注册thunk composeWithDevTools(applyMiddleware()) );
修复方案
修改Store代码,将定义好的中间件数组传入applyMiddleware即可:
import { createStore, combineReducers, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import { composeWithDevTools } from "redux-devtools-extension"; import { productListReducer } from "./reducers/productReducers"; const reducer = combineReducers({ productList: productListReducer, }); const initialState = {}; const middleware = [thunk]; const store = createStore( reducer, initialState, // 改动点:将middleware数组传入applyMiddleware composeWithDevTools(applyMiddleware(...middleware)) ); export default store;
补充说明
redux-thunk的核心作用就是识别分发的内容是否为函数:如果是函数就执行它,并把dispatch、getState作为参数传入,允许你在函数内部做异步操作后再分发普通对象类型的action;如果不是函数就直接交给reducer处理。
内容的提问来源于stack exchange,提问作者Siva Rajan
相关产品推荐
相关产品推荐

