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

调用push()函数时报错“cannot add a new property”的解决方法

修复方案

错误原因

  1. 直接修改不可变状态:polygons大概率是React状态或Redux存储的不可变对象,直接调用push修改原数组会触发不可变性校验报错。
  2. 拼写错误:代码中polygons. Coordinates多了一个空格,且属性名应为小写的coordinates(和后续代码里的polygons.coordinates保持一致)。

具体修复代码

修改saveReserve函数,通过创建副本的方式处理不可变对象,同时修正拼写错误:

const saveReserve = () => {
  if (polygons && creatingPolygon) {
    const last = creatingPolygon.coordinates[creatingPolygon.coordinates.length - 1][0][0];
    console.log({last, polygons});

    // 创建原坐标数组的副本,避免直接修改不可变状态
    const updatedPolygonCoords = [...polygons.coordinates[0][0], last];
    // 构建新的polygons基础结构,保持不可变性
    const updatedPolygonsBase = {
      ...polygons,
      coordinates: [
        [updatedPolygonCoords],
        ...polygons.coordinates.slice(1)
      ]
    };

    const oldArray: reservaLegal = {
      coordinates: [
        updatedPolygonsBase.coordinates[0],
        creatingPolygon.coordinates[0]
      ],
      type: "MultiPolygon",
    };
    setPolygons(oldArray);
    dispatch(saveLegalReserve(oldArray));
    setCreatingPolygon(null);
  } else {
    setPolygons(creatingPolygon);
    dispatch(saveLegalReserve(creatingPolygon));
    setCreatingPolygon(null);
  }
};

关键说明

  • 所有对状态对象的修改都通过解构创建副本的方式完成,确保原状态不被直接修改,符合React/Redux的不可变状态规范。
  • 修正了属性名的拼写错误,避免因属性不存在导致的额外问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 03:23:21