使用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
相关产品推荐
相关产品推荐

