arkts-no-standalone-this:禁止在独立函数和类静态方法中使用 this
解决 HarmonyOS NEXT 报错 arkts-no-standalone-this(错误码 10605093),覆盖独立函数与类 static 静态方法中误用 this 的显式传参、实例方法与箭头函数改写方案。
- 规则码
- arkts-no-standalone-this
- 错误码
- 10605093
- 级别
- error
- 适用
- API 12+ (HarmonyOS NEXT)
- 更新
- 2026/12/02
一句话排查结论
this 只能在类的实例方法和构造函数(以及其内部词法捕获的箭头函数)中使用;不要在独立函数或类的 static 静态方法中使用 this,应改为显式传入目标对象或直接引用类名。
为什么在 ArkTS 中会报这个错
依据 OpenHarmony 官方规范(错误码 10605093),ArkTS 禁止在独立函数和类的静态方法中使用 this,以避免运行时动态绑定上下文(如 call/apply/bind)带来的开销和空指针风险。
错误写法示例(TypeScript 习惯)
class Counter {
count: number = 0;
}
// 错误:独立函数内部使用 this
function increment(this: Counter): void {
this.count += 1;
}
class PageModel {
title: string = '首页';
load(): void {
// 错误:普通回调 function 内部使用 this
setTimeout(function () {
console.info(this.title);
}, 100);
}
}
正确改法(HarmonyOS NEXT 严格模式)
class Counter {
count: number = 0;
// 正确:定义为类实例方法
increment(): void {
this.count += 1;
}
}
// 或者显式将对象作为参数传入
function resetCounter(target: Counter): void {
target.count = 0;
}
class PageModel {
title: string = '首页';
load(): void {
// 正确:使用箭头函数词法捕获外层实例 this
setTimeout(() => {
console.info(this.title);
}, 100);
}
}
实际开发常见场景与避坑
- 事件监听与定时器:ArkUI 中给
onClick、setTimeout、Promise.then()传回调时,一律使用箭头函数,避免this丢失或触发规则报错。 - 禁止
call/apply/bind技巧:迁移旧前端工具库(如防抖/节流函数)时,改为闭包参数传递而非fn.apply(this, args)。
常见问题 FAQ
在普通工具函数里写 this 为什么会报错?▾
ArkTS 禁止运行时动态绑定 this(如 call/apply/bind 改变上下文),因此独立函数中的 this 没有确定归属,必须在编译期拦截。
ArkUI 组件内的回调函数里可以用 this 吗?▾
可以在组件方法内部通过箭头函数 () => { this.count++; } 捕获外层组件实例的 this,不能使用 function () { this.count++; }。
开发者资源
相关推荐阅读
- arkts-no-classes-as-obj:禁止将类(Class)本身当作普通对象传递或动态修改
arkts-no-classes-as-obj - arkts-no-structural-typing:ArkTS 不支持结构类型赋值(错误码 10605030)
arkts-no-structural-typing - arkts-no-untyped-obj-literals:对象字面量必须显式声明类型
arkts-no-untyped-obj-literals - arkts-no-obj-literals-as-types:禁止使用对象字面量作为类型声明
arkts-no-obj-literals-as-types