未捕获(承诺)类型错误:无法在 eval 中设置未定义的属性“playerName”

Bob*_*aru 2 javascript vue.js axios vuejs2

我试图response.data.Response.displayName从我的 GET 请求分配给我的 playerName 属性,但是,我收到一个错误“ Uncaught (in promise) TypeError: Cannot set property 'playerName' of undefined at eval”。我已成功进行控制台日志记录,response.data.Reponse.displayName因此其中有一个 displayName。

为什么我收到这个错误?

export default {
  data: function() {
    return {
      playerName: ''
    }
  },
  methods: {

  },
  mounted() {
    axios.get('/User/GetBungieNetUserById/19964531/')
      .then(function(response) {
          this.playerName = response.data.Response.displayName
        console.log(response.data.Response.displayName)
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*att 7

其他评论和答案是正确的 - 使用箭头/lambda 函数而不是仅仅function会起作用。但有一个细微差别,为什么。

Javascript 的概念this定义明确,但并不总是您对其他语言的期望。this当您从回调之类的子功能中执行时,可以在一个范围块内更改。在您的情况下, 中的函数then不再理解this为与直接在mounted().

但是,您可以将函数绑定到(除其他目的外)具有this无法更改的特定附加项。箭头函数隐式地执行此操作,并绑定thisthis创建箭头函数的上下文中的内容。因此,这段代码:

axios.get('/User/GetBungieNetUserById/19964531/')
  .then((response) => {
      this.playerName = response.data.Response.displayName
    console.log(response.data.Response.displayName)
  });
Run Code Online (Sandbox Code Playgroud)

this正确理解。它(大致!)等效于以下内容:

axios.get('/User/GetBungieNetUserById/19964531/')
  .then((function(response) {
      this.playerName = response.data.Response.displayName
    console.log(response.data.Response.displayName)
  }).bind(this));
Run Code Online (Sandbox Code Playgroud)