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

对象数组调用splice删除元素时报错:无法删除数组属性

数组splice删除最后一项报错:Cannot delete property '2' of [object Array]

问题详情

尝试删除数组最后一项时触发错误,相关代码及报错信息如下:

目标数组

this.customsTypes = [
    {
        "id": "D1",
        "title": "d1",
        "icon": "",
        "hasDeleteIcon": true,
        "deleteIcon": "<img src=\"assets/icons/trash_icon.svg\">"
    },
    {
        "id": "D2",
        "title": "d2",
        "icon": "",
        "hasDeleteIcon": true,
        "deleteIcon": "<img src=\"assets/icons/trash_icon.svg\">"
    },
    {
        "id": "DISTRIBUCIÓN__18/07/2023",
        "title": "Distribución  18/07/2023",
        "icon": "",
        "hasDeleteIcon": true,
        "deleteIcon": "<img src=\"assets/icons/trash_icon.svg\">"
    }
]

删除逻辑代码

const idIndex = this.customsTypes!.findIndex((e) => e.id === id);
this.customsTypes!.splice(idIndex, 1);

控制台报错

Uncaught TypeError: Cannot delete property '2' of [object Array]
at Array.splice ()


错误原因

这个报错的核心是你操作的customsTypes不是可自由修改的普通数组,大概率是以下情况:

  • 数组被Object.freeze()冻结了,冻结后的数组无法添加、删除或修改任何元素
  • 数组是只读状态(比如Vue中通过props传递的数组、Redux等状态管理库中的不可变状态,直接修改会被限制)
  • 数组的元素或length属性被设置为不可配置、不可删除

解决办法

根据不同情况对应处理:

  1. 数组被冻结/需要保持不可变:先创建数组副本,修改副本后再赋值回原变量
    // 浅拷贝创建副本
    const tempArr = [...this.customsTypes];
    const idIndex = tempArr.findIndex(e => e.id === id);
    // 先判断索引有效再操作,避免无效索引报错
    if (idIndex !== -1) {
        tempArr.splice(idIndex, 1);
        this.customsTypes = tempArr;
    }
    
  2. Vue响应式数组:如果是组件props传入的数组,不要直接修改原数组,通过父组件修改数据源;如果是本地响应式数组,也可以用上述副本赋值的方式触发视图更新
  3. 检查属性配置:可以通过Object.getOwnPropertyDescriptor(this.customsTypes, '2')查看索引2对应的元素配置,若configurable为false,同样需要通过副本修改

额外提醒:调用splice前一定要判断idIndex不等于-1,避免传入无效索引引发其他异常;TypeScript中的非空断言!要确保变量确实不为null/undefined。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:01:12