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

React Native使用Redux报Actions must be plain objects错误求助

React Redux 报错 Error: Actions must be plain objects. Instead, the actual type was: 'string'. You may need to add middleware 修复方案

你的代码存在5处不符合Redux运行规则的问题,按以下顺序修正即可解决报错,和redux-thunk依赖本身无关:

1. Action Creator 返回值不符合规范

Redux 要求同步action必须返回带type字段的普通对象,你当前的action直接返回字符串类型,是触发本次报错的核心原因。
修正后action.js代码:

export const AddNow =()=>{
    return {
      type: "ADD_NUM"
    }
}

export const DelNow =()=>{
  return {
    type: "DEL_NUM"
  }
}

2. Dispatch 调用时未执行action函数

你在组件中传给dispatch的是AddNow函数本身,没有加()执行函数获取action对象,实际传入dispatch的是函数引用,不符合要求。
修正后组件调用代码:

import { AddNow , DelNow} from "../../actions";
import {useDispatch} from 'react-redux'
 
const dispatch = useDispatch();
<CustomBTN 
      onPress={()=>{dispatch(AddNow()) }}
/>

3. combineReducers 配置错误

合并reducer时引用了未定义的变量cartIMyBooktems,没有正确挂载你编写的MyBook reducer,运行时会触发变量未定义异常。
修正后reducer/index.js代码:

import MyBook from "./MyBook";
import {combineReducers} from 'redux';

const rootreducers=combineReducers({
  myBook: MyBook // key为store中该状态的访问字段名,可自定义
})

export default rootreducers;

4. Reducer 状态更新逻辑错误

状态更新时使用了固定初始值initialState计算,而非当前传入的state参数,会导致多次加减操作时数值不会持续变化,始终固定为31/29。
修正后reducer/MyBook.js代码:

const initialState = 30;
const MyBook = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_NUM":
      return state +1;
    
    case "DEL_NUM":
      return state -1;
    default:
      return state;
  } 
};

export default MyBook

5. Store 导出写法不规范

原代码在导出语句中直接给未声明的store变量赋值,严格模式下会触发语法错误。
修正后store/index.js代码:

import {createStore,applyMiddleware} from 'redux';
import thunk from 'redux-thunk'; 
import rootreducers from '../reducers/index';

const store = createStore(rootreducers, applyMiddleware(thunk));
export default store;

额外注意

useDispatch属于React Hook,必须在函数组件/自定义Hook的顶层作用域调用,不能放在循环、条件判断、嵌套函数内部,否则会触发Hook规则报错。

内容的提问来源于stack exchange,提问作者Rahul Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 03:36:34