You need to enable JavaScript to run this app. Chrome扩展存储对象时报Cannot read property 'push' of undefined如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展存储对象时报Cannot read property 'push' of undefined如何解决

报错原因

报错核心是myObjArray调用push方法时为undefined,同时代码还存在隐藏的存储键名错误:

  • 首次调用updateLocalChromeStorage时,chrome.storage.local中还没有对应的存储键,result[key]返回undefined,直接赋值会覆盖你初始化的空数组,导致调用push时报错。你写的if(result)判断没有意义,chrome.storage.local.get的回调参数result永远是对象,哪怕没有匹配的键也不会为空。
  • 存储时写的{ key: myObjArray }属于对象字面量写法,实际存到storage里的键名是固定的"key",不是你传入的动态参数key的值,也会导致后续取值永远拿不到正确的数组。

修复方案

修改updateLocalChromeStorage函数即可:

function updateLocalChromeStorage(key, obj) {
    chrome.storage.local.get(key, function (result) {
        // 兜底判断:如果已有值不是数组就用空数组
        const myObjArray = Array.isArray(result[key]) ? result[key] : [];
        myObjArray.push(obj);
        // 用计算属性设置动态键名
        chrome.storage.local.set({ [key]: myObjArray });
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 14:15:04