如何解决LocalStorage存储function报错问题
==============================

#### 问题现象

使用LocalStorage传递function报错：

Error message:@Component 'owning @Component UNKNOWN': Illegal variable value error with decorated variable undefined 'clickSend': failed validation: 'undefined, null, number, boolean, string, or Object but not function, not V2 @ObservedV2 / @Trace class, and makeObserved return value either, attempt to assign value type: 'function', value: 'undefined'!

关键问题参考如下：

function openCommentsInput(title: string, hintMsg: string, clickSend: Function \= (content: string) \=\> {}) {
  let storage: LocalStorage \= new LocalStorage();
  storage.setOrCreate('title', title)
  storage.setOrCreate('hintMsg', hintMsg)
  storage.setOrCreate('clickSend', clickSend) _// 程序崩溃，报错_
}

#### 背景知识

[LocalStorage](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-localstorage)是页面级的UI状态存储，存储的类型有所限制。

#### 问题定位

查看以下报错日志的关键信息可知，clickSend是非法变量值，支持undefined、null、number、boolean、string、Object等类型，但不支持function函数类型变量。

Illegal variable value error with decorated variable undefined 'clickSend': failed validation: 'undefined, null, number, boolean, string, or Object but not function ...'

#### 分析结论

LocalStorage不支持存储function函数类型变量。

#### 修改建议

使用类class将函数function进行封装为Object对象，LocalStorage支持存储Object对象。

let storage: LocalStorage \= new LocalStorage();

function openCommentsInput(title: string, hintMsg: string, clickSend: object) {
  storage.setOrCreate('title', title);
  storage.setOrCreate('hintMsg', hintMsg);
  storage.setOrCreate('clickSend', clickSend);
}

_//_ _使用class对function进行一层封装_
class MyFunc {
  clickSend: Function \= () \=\> {
  };
}

_//_ _需要保存至LocalStorage的函数_
function clickSend(ctx: string) {
  console.info(ctx);
}

@Entry(storage)
@Component
export struct LocalStorageDemo {
  @LocalStorageLink('clickSend') myFunc: object \= \[\]; _//_ _获取LocalStorage中存储的clickSend对象_

  build() {
    Column({ space: 20 }) {
      Button('向storage保存数据')
        .onClick(() \=\> {
          let myFunc: MyFunc \= new MyFunc();
          myFunc.clickSend \= clickSend; _// 将要保存的函数封装在class对象中_
          openCommentsInput('title', 'hintMsg', myFunc); _//_ _将class对象保存至LocalStorage_
        });
      Button('读取storage的数据')
        .onClick(() \=\> {
          let tmp \= this.myFunc as MyFunc; _// 将Object对象转为MyFunc类_
          tmp.clickSend('读取storage的数据成功'); _//_ _调用MyFunc中的clickSend函数_
        });
    };
  }
}

运行截图如下：成功调用LocalStorage中存储的类对象的函数来打印数据。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/ae/v3/Rnc9X2JTSiqZceAQrXHGoQ/zh-cn_image_0000002658835373.png?HW-CC-KV=V1&HW-CC-Date=20260709T134034Z&HW-CC-Expire=86400&HW-CC-Sign=CEBEF6081037C7FDB0D928014276AB6788CA2655E86EF95BD0550BF924DBE0E0 "点击放大")