React-Redux报Actions must be plain objects错误如何解决?
错误原因
Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions
这个报错的核心是:你已经配置了redux-thunk中间件,但异步action creator的写法不符合thunk规范。
Redux默认只接收普通对象作为action,你当前写的getChartData是async函数,直接执行会返回Promise实例,不是普通对象,也不符合thunk要求的「返回一个接收dispatch为参数的函数」的规则,所以触发报错。
修正方案
1. 调整异步action creator写法
按照thunk的要求,action creator要返回一个参数为dispatch的函数,异步逻辑写在这个函数内部,得到结果后手动调用dispatch提交action:
import axios from "axios"; import { GET_CHART_DATA, GET_CHART_DATA_ERROR } from "../actionTypes"; export const getChartData = () => async (dispatch) => { try { const { data } = await axios.get( "https://example.com/api" ); console.log("data", data); // 拿到结果后手动dispatch action dispatch({ type: GET_CHART_DATA, payload: data }); } catch (error) { dispatch({ type: GET_CHART_DATA_ERROR, error: error }); } };
2. 简化dispatch触发逻辑
不需要自己在组件内封装async自执行函数,thunk中间件会自动处理action creator返回的函数内部的异步逻辑,直接调用dispatch即可:
const dispatch = useDispatch(); useEffect(() => { dispatch(getChartData()); }, [dispatch]);
额外说明
你现有的reducer代码和store配置代码无需修改,上面两处调整后即可解决报错。如果需要更完善的状态管理,可以在reducer中新增loading、error字段区分请求状态,方便组件渲染不同的交互反馈。
内容的提问来源于stack exchange,提问作者Yogeshwar Chaturvedi
相关产品推荐
相关产品推荐

