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

React/Redux新手使用combineReducers遇报错:Cannot convert undefined or null to object

解决combineReducers触发的Uncaught TypeError问题

嘿,我来帮你搞定这个坑!你碰到的这个错误,核心原因是你的reducer代码存在两处问题,导致使用combineReducers时返回了undefined——而Redux的combineReducers要求每个reducer必须始终返回一个有效的state值,绝对不能是undefined或null。

问题排查

先看你给出的articleReducer代码,两个明显的问题:

  1. 语法错误:在返回新state的语句里,action.payload后面多了个多余的点,还漏写了数组的闭合方括号,导致代码无法正确解析执行。
  2. 缺失default分支:你的switch语句只处理了ADD_ARTICLE类型的action,当其他类型的action触发时,reducer没有返回任何值(也就是默认返回undefined),这正是触发报错的关键原因。

修复后的完整代码

把你的reducers\article.js改成下面这样:

import { ADD_ARTICLE } from "../actiontypes/action-types";

const initialState = { articles: [] };

const articleReducer = (state = initialState, action) => {
  switch (action.type){
    case ADD_ARTICLE:
      // 修复语法错误:去掉多余的点,补上数组闭合方括号
      return {...state, articles: [...state.articles, action.payload]};
    // 必须添加default分支,默认返回原state,确保任何情况都有有效返回值
    default:
      return state;
  }
};

export default articleReducer;

额外验证点

另外,确保你在使用combineReducers时正确配置了这个reducer,比如在根reducer文件里:

import { combineReducers } from 'redux';
import articleReducer from './article';

const rootReducer = combineReducers({
  articles: articleReducer // 这里的key可以自定义,后续取state时对应上就行
});

export default rootReducer;

这样修改后,你的reducer就会始终返回一个有效的state对象,combineReducers也就不会再抛出那个类型错误啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:04:40