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

React项目Redux Toolkit配置报错:Expected the reducer to be a function

解决Redux Toolkit报错“Expected the reducer to be a function”

报错原因

  1. Slice导出错误:直接将Redux Toolkit创建的slice对象作为reducer传入,而非使用slice的.reducer属性
  2. Store配置错误:仍沿用旧Redux的createStore方法,未使用Redux Toolkit的configureStore,且reducer组合逻辑错误
  3. 导入路径/导出方式错误:reducer导入时路径错误,或slice未正确导出reducer

解决步骤

1. 修正authSlice的导出逻辑

确保slice正确创建并导出reducer,示例代码:

// store/authSlice.js
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  user: null,
  isLoading: false,
  error: null
};

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    loginStart: (state) => { state.isLoading = true; },
    loginSuccess: (state, action) => {
      state.isLoading = false;
      state.user = action.payload;
      state.error = null;
    },
    loginFailure: (state, action) => {
      state.isLoading = false;
      state.error = action.payload;
    }
  }
});

// 导出action creators
export const { loginStart, loginSuccess, loginFailure } = authSlice.actions;
// 关键:导出slice的reducer,而非整个slice对象
export default authSlice.reducer;

2. 用Redux Toolkit正确配置Store

使用configureStore替代旧的createStore,它会自动集成thunk、devTools等功能:

// store/index.js
import { configureStore } from '@reduxjs/toolkit';
// 导入正确导出的auth reducer
import authReducer from './authSlice';

export const store = configureStore({
  reducer: {
    // 将auth reducer挂载到auth命名空间下
    auth: authReducer
  }
});

3. 清理旧代码残留

原项目使用Redux Thunk,可能存在旧的createStore/combineReducers错误用法,比如:

// 错误示例:传入slice对象而非reducer
import { createStore, combineReducers } from 'redux';
import authSlice from './authSlice';

const rootReducer = combineReducers({
  auth: authSlice // 错误:应该是authSlice.reducer
});
const store = createStore(rootReducer);

如果需要保留combineReducers,需确保传入的是reducer:

// 正确用法(可选)
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import authReducer from './authSlice';

const rootReducer = combineReducers({
  auth: authReducer
});

const store = configureStore({
  reducer: rootReducer
});

4. 确认组件中Store的挂载

在项目入口文件正确挂载store:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';

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

内容的提问来源于stack exchange,提问作者Mohamed Amine Boudagga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:47:18