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

为什么调用Redux的dispatch()会给对象额外添加undefined属性?

问题描述

我正在处理一个对象,要通过Redux执行dispatch,使用的代码如下:

const objMap = {};
const propList = ['apple', 'banana'];

for (const prop of propList) {
   objMap[prop] = 0;
}
console.log("thunk2: ", materialMap);
dispatch(reduxActions.updateCount({ objMap }));

不执行dispatch();代码行时,输出结果为:

{
  "apple": 0,
  "banana": 0,
}

但**执行dispatch()**后,返回的结果会多出一个'undefined'属性,如下所示:

{
    "apple": 0,
    "banana": 0,
    "undefined": null
}

请问为什么会额外添加这个undefined属性?

注:示例代码中console.log打印的materialMap和定义的objMap变量名不一致,属于笔误,排查时请先确认实际代码中操作的变量名是否正确。


原因及排查方案

多余的undefined属性并非dispatch方法本身添加,问题完全出在reduxActions.updateCount对应的逻辑(包括action creator、reducer处理函数)中,常见错误场景如下:

  • 场景1:reducer中错误使用undefined作为键赋值
    处理updateCountaction的reducer中存在动态键赋值逻辑,且作为键的变量值为undefined,示例错误代码如下:
    const updateCountReducer = (state, { payload }) => {
      // 错误:读取payload中不存在的属性作为键,得到undefined
      const dynamicKey = payload.nonExistentProp
      return {
        ...state,
        // 用undefined作为键赋值,会自动转为字符串"undefined"作为属性名
        [dynamicKey]: null
      }
    }
    
    该场景生成的结果和你遇到的输出完全一致。
  • 场景2:action creator处理入参时出错
    如果reduxActions.updateCount是自定义的action creator,可能内部对入参做了错误处理:比如尝试从入参中读取某个属性作为新增键,读取不到得到undefined后,将该键值对塞进了传给reducer的payload中,最终被合并到状态里。
  • 场景3:运行时propList存在undefined元素
    你给出的示例中propList是写死的固定值,若实际运行时propList是从接口、其他变量动态获取的,内部存在undefined元素,遍历赋值时也会生成undefined属性,但你确认不执行dispatch时输出正常,可直接排除该场景。

快速排查方法

在reduxActions.updateCount逻辑的第一行加断点或打印传入的objMap:

  1. 如果进入逻辑时objMap已经存在undefined属性:检查dispatch之前所有操作objMap的逻辑,找到额外赋值的位置
  2. 如果进入逻辑时objMap正常:逐行检查updateCount的action creator和对应reducer代码,定位所有动态给对象赋值键的逻辑,确认键变量不会出现undefined的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:06:02