首页 > 解决方案 > 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... 的正上方,它似乎工作正常。

标签: javascriptvuejs2

解决方案


我很有信心这是一个变量范围问题,但我不完全确定如何描述它。

基本上,传递给的匿名函数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(); 
}

推荐阅读