You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:调用API成功后赋值this.channels触发TypeError(无法用箭头函数)

问题分析

报错TypeError: Cannot set properties of undefined (setting 'channels')的核心原因是:普通回调函数内部的this指向的是该函数自身的执行上下文,而非你期望的外部对象(比如组件实例),此时this为undefined,自然无法赋值channels属性。

解决方案(无法使用箭头函数时)

由于平台限制不能用箭头函数,可以通过以下两种方式修正作用域:

方法1:提前缓存外部this到变量

在回调函数外,将外部作用域的this缓存到一个变量(比如that/self),回调内使用这个变量访问外部对象:

var that = this;
MockDataService.getChannelData(function(response){
    if(response){
        that.channels = response;
    }
});

方法2:用bind()绑定回调函数的this

通过Function.prototype.bind()方法,将回调函数的this强制绑定为外部作用域的this:

MockDataService.getChannelData(function(response){
    if(response){
        this.channels = response;
    }
}.bind(this));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:30:56