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

迁移至Redux Toolkit时出现action不可序列化报错且devtools类型为undefined

问题原因

你遇到的报错和DevTools显示异常由三个错误点共同导致:

  1. Redux Toolkit的action creator使用错误
    你直接把registerSuccess、registerFail这两个action creator函数赋值给了dispatch的type字段,type要求是字符串格式,函数属于不可序列化值,所以触发了非序列化值检测报错,也导致DevTools识别不到正确的action类型。
  2. reducer内的状态更新语法错误
    auth的初始state是对象类型,但你在registerSuccess里用了数组专属的push方法更新状态,会触发隐式异常。
  3. 请求头拼写错误
    你配置的comtent-Type拼写错误,正确值为Content-Type,可能导致后端无法正常解析请求参数。

修复方案

1. 修正dispatch调用逻辑

RTK的action creator调用后才会返回标准action对象,不需要手动构造type和payload结构,直接传调用结果给dispatch即可:

  • 成功请求分支改写成dispatch(registerSuccess(res.data))
  • 失败请求分支改写成dispatch(registerFail())

2. 修正registerSuccess reducer的状态更新逻辑

registerSuccess: (state, action) => {
  // 直接从action.payload取返回值即可,不需要多层解构
  const payload = action.payload;
  state.token = payload.token;
  state.isAuthenticated = true;
  state.loading = false;
  state.user = payload.user;
},

3. 简化请求逻辑

axios发送post请求默认会自动序列化JSON对象、添加Content-Type: application/json请求头,不需要手动处理。

完整修正后代码

import axios from 'axios';
import { createSlice } from '@reduxjs/toolkit';
import { setAlert } from '../alerts/alertSlice';

const slice = createSlice({
  name: 'auth',
  initialState: {
    token: localStorage.getItem('token'),
    isAuthenticated: null,
    loading: true,
    user: null,
  },
  reducers: {
    registerSuccess: (state, action) => {
      const payload = action.payload;
      state.token = payload.token;
      state.isAuthenticated = true;
      state.loading = false;
      state.user = payload.user;
    },
    registerFail: (state) => {
      localStorage.removeItem('token');
      state.token = null;
      state.isAuthenticated = false;
      state.loading = false;
      state.user = null;
    },
  },
});

const { registerSuccess, registerFail } = slice.actions;

export default slice.reducer;

// Register User
export const register =
  ({ name, email, password }) =>
  async (dispatch) => {
    try {
      const res = await axios.post('/api/users', { name, email, password });
      dispatch(registerSuccess(res.data));
    } catch (err) {
      const errors = err.response.data.errors;
      if (errors) {
        errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
      }
      dispatch(registerFail());
    }
  };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:45:04