Button('更新')
  .width('100%')
  .height(48)
  .onClick(this.updateOrder);

可以这样用

  updateOrder = async () => {
    this.a='aaaa'


  };

却不可以这样用

updateOrder(){
    this.a='aaa'
  }

原因是:

这是 ArkTS/JS 的 this 绑定机制造成的:

你的问题核心其实是:

为什么 updateOrder = async () => {} 可以正常更新 UI,而普通函数 k() 却不能?

原因非常明确:

✅ 1. 箭头函数会自动绑定当前组件实例(不丢 this)

你写的:

updateOrder = async () => { }

这是 箭头函数它自动捕获当前词法作用域的 this

也就是说:

  • updateOrder 中的 this 永远指向 test3oo 组件实例

  • 所以在 onClick 中这样写 不会丢失 this

Button('更新').onClick(this.updateOrder)

updateOrder 中的状态修改会立即触发 UI 刷新
因为 ArkUI 的 @State 工作正常。


❌ 2. 普通函数不会绑定 this,会在调用时丢失

你原来的:

k() {
  this.a = 'aaa'
}

这是普通函数。

当你这样绑定时:

Button('韩式器').onClick(this.k)

ArkUI 在触发回调时实际是这样调用的:

callback()   // 不是 this.k()

所以 this 指向 window / undefined / 框架内部,不是组件实例

自然:

  • this.a → 不是组件的 a

  • @State 根本没改

  • UI 自然不会刷新


🔍 3. 对比:箭头函数 vs 普通函数

写法 this 是否绑定 UI 是否能更新
updateOrder = async () => {} ✔ 绑定组件实例 ✔ 能更新
k() {} ✘ 不绑定 this ❌ 无法更新
.onClick(this.k) ❌ this 丢失 ❌ 无法更新
.onClick(() => this.k()) ✔ this 正确 ✔ 能更新

🟦 4. 因此:你 updateOrder 能用,是因为它是箭头函数

箭头函数 = 词法绑定 this
普通函数 = 运行时绑定 this(很容易丢)


🧩 5. 最实用的写法(工程最佳实践)

写法 1(推荐):所有事件回调都使用箭头函数属性

k = () => {
  this.a = 'aaa';
}

updateOrder = async () => {
  // ...
}

这样写你永远不会有 this 问题。

写法 2:或者使用箭头包裹普通函数

Button('韩式器')
  .onClick(() => this.k())

🟢 总结

updateOrder = async () => {} 用得了,是因为 箭头函数自动绑定 this
k() 用不了,是因为 普通函数在事件回调中 this 丢失


Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐