JS类嵌套函数中能否使用this?有哪些正确的替代写法?
警告触发原因
你遇到的IDE警告本质是无法确认嵌套函数内的this是否指向类实例:你当前代码中flow接收的是普通生成器函数,其内部this指向未明确绑定到类实例,即使内层then回调使用了箭头函数继承外层作用域的this,也无法保证最终访问的是类字段,因此IDE会抛出有效性校验警告。
符合规范的解决方法
以下几种写法都可以解决该问题,可按使用习惯选择:
- 方法1:提前缓存外层作用域的
this(兼容性最高,无需修改原有代码结构)
fetchStickyAppointment = flow(function* () { // 顶部缓存类实例指向 const that = this; fetch(/api/) .then(response => response.json()) .then(data => { if (+data?.id > 0) { that.stickyAppointment = that.currentAppointment = data; } else { that.stickyAppointment = data; that.currentAppointment = that.findCurrentAppointment(); } }); })
- 方法2:给生成器函数绑定类实例
this,保证内层继承的指向正确
// 末尾添加.bind(this)绑定类实例指向 fetchStickyAppointment = flow(function* () { fetch(/api/) .then(response => response.json()) .then(data => { if (+data?.id > 0) { this.stickyAppointment = this.currentAppointment = data; } else { this.stickyAppointment = data; this.currentAppointment = this.findCurrentAppointment(); } }); }.bind(this))
- 方法3:配合
flow的特性用yield替代then链式调用,代码更简洁易读(如果是MobX的flow工具,更推荐该写法)
fetchStickyAppointment = flow(function* () { const response = yield fetch('/api/') const data = yield response.json() if (+data?.id > 0) { this.stickyAppointment = this.currentAppointment = data; } else { this.stickyAppointment = data; this.currentAppointment = this.findCurrentAppointment(); } }.bind(this))
嵌套函数访问类字段的规则说明
嵌套函数内部可以直接用this访问类字段,但需要满足两个前提:
- 嵌套函数外层作用域的
this已经正确绑定到类实例 - 如果嵌套函数是普通函数,需要主动绑定
this指向,优先使用箭头函数继承外层已绑定正确的this,避免调用时指向发生变化
内容的提问来源于stack exchange,提问作者Rafath
相关产品推荐
相关产品推荐

