You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Redux报错:Actions must be plain objects 求解决方案

解决Redux报错:Actions must be plain objects. Use custom middleware for async actions.

Hey,我看了你的代码和遇到的报错,马上就发现了两个关键问题,咱们一步步来修复:

1. Fetch响应没正确解析成JSON对象

你的fetchData action里,直接把fetch返回的posts(这其实是个Response实例对象,不是Redux要求的纯对象)dispatch出去了,这就触发了那个报错。你需要先调用.json()方法把响应转换成JSON格式的数据:

修改后的actions代码:

import {FETCH_DATA} from './types';

export const fetchData = () => dispatch => {
  fetch('https://raw.githubusercontent.com/CodeNinja1395/Test-task-for-inCode/master/clients.json')
    // 新增这一步:把响应解析成JSON
    .then(response => response.json())
    .then(posts => dispatch({
      type: FETCH_DATA,
      payload: posts
    }))
    // 建议加上错误处理,避免请求失败时毫无反馈
    .catch(error => console.error('请求数据失败:', error));
};

2. 确认Thunk中间件的配置和依赖没问题

你的store配置代码看起来是对的,但要再确认两个点:

  • 已经通过npm install redux-thunk或者yarn add redux-thunk安装了redux-thunk依赖(没装的话赶紧装)
  • 确保在项目入口文件(比如index.js)里,把store正确传递给了Redux的Provider组件,示例代码如下:
import { Provider } from 'react-redux';
import store from './store'; // 替换成你的store文件路径

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

额外的调试小建议

如果上面的修改后还是有问题,可以检查这些地方:

  • 组件里调用fetchData的方式:必须通过dispatch(fetchData())触发,不能直接调用fetchData()
  • 你的reducer是否正确处理了FETCH_DATA action:要确保返回新的状态对象,不能直接修改原状态
  • 如果用Redux DevTools,可以把store配置改成兼容DevTools的版本,方便调试:
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const initialState = {};
const middleware = [thunk];

// 兼容Redux DevTools的增强器配置
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  rootReducer,
  initialState,
  composeEnhancers(applyMiddleware(...middleware))
);

export default store;

按照上面的步骤改完,应该就能解决这个报错了。如果还有问题,可以再检查一下项目里的其他关联代码~

内容的提问来源于stack exchange,提问作者袚褉懈褕邪 袣懈褋械薪泻芯

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:13:19