javascript - Vue 事件中令人困惑的错误 Uncaught (in promise) TypeError: _this.$auth.getAccessToken(...).then is not a function
问题描述
在此之前,我是 JS 编程的新手,我是 .net 人,所以这可能是混乱的根源。
在我的 PageLayout.vue 上,在创建的事件中,我正在尝试进行身份验证(使用 okta)
我得到的错误是:
Uncaught (in promise) TypeError: _this.$auth.getAccessToken(...).then is not a function at eval (PageLayout.vue?66f1:87)
但是在 getAccessToken 的调用之上,对 this.$auth.GetUser() 的调用是成功的,我们实际上是在该方法的 then 调用中。
then 调用中的 this 是否更改范围?
那为什么 this.$store.commit('SET_OKTA_USER', user) 在它之前就成功了?
created() {
this.$store.commit('SET_LOADING_APP', true)
this.$auth.getUser().then((user) => {
// Set Okta user
if (user == null && user == undefined) {
// no user
this.$store.commit(
'SET_RESPONSE_MSG',
'Okta user is null or undefined.'
)
this.$store.commit('SET_RESPONSE_TYPE', 'error')
} else {
// store user
this.$store.commit('SET_OKTA_USER', user)
// store token
this.$auth.getAccessToken().then((token) => { //<---------blow up here saying it's not a function.
this.$store.commit('SET_ACCESS_TOKEN', token)
localStorage.setItem('token', JSON.stringify(token))
apiClient.defaults.headers.common.Authorization = `Bearer ${token}`
})
// adName
const adName = user.preferred_username.substr(
0,
user.preferred_username.indexOf('@')
)
this.$store.commit('SET_AD_NAME', adName)
this.getUserInfo(adName)
}
})
},
我不知道为什么上面的代码是有效的,但 getAccessToken 不是。
ifi 粘贴
const accessToken = this.$auth.getAccessToken();
if (accessToken != undefined)
{
this.setUserToken(accessToken);
this.getUserInfo(this.$store.state.adName);
}
在 this.$auth.getAccessToken().then... 的正上方,它似乎工作正常。
解决方案
我很有信心这是一个变量范围问题,但我不完全确定如何描述它。
基本上,传递给的匿名函数then
是创建一个新的私有作用域,
this.$auth.getUser().then((user)=>{
//this no longer exists like you expect it to
});
我想到的最简单的解决方案是将您的created()
方法更改为异步,以便您可以将其重新设计为如下所示:
async created(){
let user = await this.$auth.getUser();
//do some stuff
let token = await this.$auth.getAccessToken();
}
推荐阅读
- laravel - Laravel Eloquent groupby 和 sum
- excel - 更改所选单元格字符的颜色和大小(如果未选中则返回初始状态)
- javascript - 在for循环中将给定两个数字之间的所有数字相乘
- ios - 代码签名“PryntTrimmerView.framework”失败
- python-3.x - 图像调整大小,IndexError:列表分配索引超出范围
- laravel - 如果当前请求尚未完成,则阻止用户发送新请求
- angular-material - Angular 6 - 基于单选按钮部分显示表单组件
- hyperledger-fabric - 分布式账本将存储在超级账本作曲家和结构中的位置
- hyperledger-composer - 如何在 Hyperledger-composer 中查询相似词?
- r - 如果语句给了我几个警告它们是什么意思?