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

使用MSAL获取Azure API访问令牌时报Cannot set property 'authToken' of undefined错

问题排查与解决方案

错误原因

该报错是this作用域绑定错误导致:你在acquireTokenSilent的then、catch回调中使用了普通匿名函数,普通函数的this指向运行时的调用上下文,在严格模式下该上下文默认值为undefined,因此尝试访问this.authToken时触发报错。

修复方案

推荐以下三种修复方式,优先选择箭头函数方案:

  • 方案1:使用箭头函数替换普通匿名函数
    箭头函数会继承外层作用域的this指向,自动绑定当前类的实例,无需额外处理:
gettoken() {
  this.authService.acquireTokenSilent(tokenRequest)
  .then((tokenResponse) => {
    console.log(tokenResponse.accessToken);
    this.authToken = tokenResponse.accessToken;
  })
  .catch((error) => {
    console.log(error);
  });
}
  • 方案2:提前保存外层this到临时变量
    在回调外层将类实例的this赋值给临时变量,回调中直接使用临时变量访问类属性:
gettoken() {
  // 提前保存类实例指向
  const that = this;
  this.authService.acquireTokenSilent(tokenRequest)
  .then(function (tokenResponse) {
    console.log(tokenResponse.accessToken);
    that.authToken = tokenResponse.accessToken;
  })
  .catch(function (error) {
    console.log(error);
  });
}
  • 方案3:手动给回调函数绑定this
    使用bind方法手动将回调的this绑定为当前类实例:
gettoken() {
  this.authService.acquireTokenSilent(tokenRequest)
  .then(function (tokenResponse) {
    console.log(tokenResponse.accessToken);
    this.authToken = tokenResponse.accessToken;
  }.bind(this))
  .catch(function (error) {
    console.log(error);
  }.bind(this));
}

内容的提问来源于stack exchange,提问作者Jonald Monday

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 13:51:03