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

Redux Toolkit用Immer仍触发状态变更错误,求问题排查

Redux Toolkit Immer切片状态变更检测错误排查

问题描述

使用Redux Toolkit的Immer slice,按允许的方式修改状态,但收到状态变更检测错误,不确定是否是reducer问题,也想确认是否遗漏了ESLint规则。

错误信息

Error: Invariant failed: A state mutation was detected between dispatches, in the path 'components.component_159275.input.options'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)

调用代码

reduxDispatch(updateValue({ componentId, value }));

Slice代码

export const componentsSlice = createSlice({
  name: 'COMPONENTS',
  initialState: defaultState.components,
  reducers: {
    updateValue(state, action) {
      const { payload } = action;
      const { componentId, value } = payload;
      state[`component_${componentId}`].component.input.value = value;
    },
  },
});

ESLint配置

"no-param-reassign": [ // allows us to reassign where the param which is used in that is state or ctx.
  "error",
  { "props": true, "ignorePropertyModificationsFor": ["state", "ctx"] }
],

解答

你的reducer写法符合Immer的要求,ESLint配置也没有问题,不需要额外添加规则。

报错路径是components.component_159275.input.options,但当前reducer只修改了input.value,说明问题出在其他代码逻辑:

  • Redux Toolkit默认会冻结状态,只有在reducer执行期间,Immer才允许通过“可变”语法修改状态。如果在reducer之外直接修改状态对象的属性(比如组件里直接赋值、异步逻辑中操作state),就会触发这个不变性错误。
  • 你需要排查代码中所有对input.options的修改操作,确保所有状态变更都通过Redux的action和reducer完成,不能直接修改从store获取的状态对象。

排查建议:

  • 全局搜索代码中input.options的赋值操作,定位非reducer内的修改逻辑。
  • 使用Redux DevTools的记录功能,追踪触发mutation错误的具体操作,找到对应的代码位置。
  • 确认所有组件中都是通过dispatch action来修改状态,而非直接操作从useSelector获取的state。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:50:41