You need to enable JavaScript to run this app. Angular中使用getter/setter读写缓存时报TypeError: this.saveCache不是函数
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用getter/setter读写缓存时报TypeError: this.saveCache不是函数

报错原因

出现this.saveCache is not a function的核心诱因有两个:

  • 类内部声明了和存取器同名的普通成员属性,直接覆盖了你定义的get/set缓存读写逻辑
  • 错误把saveCache这个存取器当成普通可调用函数,使用括号传参的方式触发逻辑,而不是用属性赋值的正确语法
修正步骤
  • 移除类内同名属性的冲突覆盖
    绝对不要在类的属性定义区域单独声明和存取器同名的saveCache普通字段,这类普通属性定义会完全覆盖类上的get/set存取器,导致原有缓存逻辑失效。
    ❌ 错误示例:
    export class AppComponent {
      // 这行普通属性定义会完全覆盖下方的get/set逻辑
      public saveCache: any;
    
      get saveCache(): any {
        if (localStorage.getItem('saveCache') === null) {
          return null;
        }
        return JSON.parse(localStorage.getItem('saveCache'));
      }
    
      set saveCache(value:any) {
        localStorage.setItem('saveCache', JSON.stringify(value));
      }
    }
    
  • 修正存取器的调用语法
    类的get/set存取器本质是类上的特殊属性,不是可调用的函数,必须通过属性的读写语法触发,不能加括号当函数传参:
    • ❌ 触发报错的错误写法:this.saveCache({ key: 'test' })(将存取器当普通函数传参调用)
    • ✅ 正确触发setter的写法:直接用等号赋值 this.saveCache = { key: 'test' }
    • ✅ 正确触发getter的写法:直接读取属性 const cacheData = this.saveCache
可优化的健壮性改造

原有存取器代码缺少异常捕获,一旦localStorage中存储的saveCache值不是合法JSON,JSON.parse会直接抛出语法错误导致程序崩溃,可以改造为:

get saveCache(): any {
  const rawCache = localStorage.getItem('saveCache');
  if (!rawCache) return null;
  try {
    return JSON.parse(rawCache);
  } catch (err) {
    return null;
  }
}

set saveCache(value: any) {
  if (value === null || value === undefined) {
    localStorage.removeItem('saveCache');
    return;
  }
  localStorage.setItem('saveCache', JSON.stringify(value));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 21:54:03