obj 有时是未定义的,其他时候可以完美运行

obj is undefined sometimes and works perfectly other times

在计算属性中,我尝试将从 API 收到的 ID 与对象数组进行匹配,ID 键也从 API 收到,并从匹配的 ID 中检索名称键对象。

obj 变量偶尔会抛出 "obj is undefined" 错误,但并不总是如此。

我认为这与 ID 异步有关。将函数从箭头更改为经典函数,以免混淆 this 范围。

  data() {
    return {
      upComing: [],
      popular: [],
      topRated: [],
      playingNow: [],
      details: [],
      genres: []
    }
  },

  computed: {
    genre: function() {
      let list = this.upComing[0] ? this.upComing[0].genre_ids[0] : 0
      let obj = this.genres.find(function(o) {
        return o.id === list
      })
      return obj.name
    }
  },

  created() {
    let self = this
    APIService.getUpcoming()
      .then(response => {
        self.upComing = response.data.results
        //console.log(this.upComing)
      })
      .catch(error => {
        console.log(`There was an error: ${error.response}`)
      }),
      APIService.getGenres()
        .then(response => {
          this.genres = response.data.genres
          //console.log(this.genres)
        })
        .catch(error => {
          console.log(`There was an error: ${error.response}`)
        })
  }
}

我明白这个 TypeError: "obj is undefined" 和这个 [Vue warn]: Error in render: "TypeError: obj is undefined"

并且它每次抛出它们两次。所以我在控制台中有 4 个错误,但只有这 2 个错误,延迟 1 秒。

你很可能对异步问题的看法是正确的,难道你不能通过做这样的事情来防止undefined

  computed: {
    genre: function() {
      let list = this.upComing[0] ? this.upComing[0].genre_ids[0] : 0
      let obj = this.genres.find(function(o) {
        return o.id === list
      })
      return obj ? obj.name : '' // or whatever should be the default
    }
  },

错误是this.genres[],所以计算的属性是在你的组件挂载时计算的,所以this.genres.find(....的结果是未定义的(因为它无法在空列表中找到内容)。

您可以使用像这样的 || 符号来获得默认值:

let obj = this.genres.find(function(o) {
        return o.id === list
      }) || { name: 'defaultName'}

这意味着如果在流派列表中没有找到任何内容,您仍然有一个默认结果,那么您可以 return obj.name 而不会出现错误。

另请注意,genres 变量为空,因为计算方法在您的 promise 解决之前被 tun,并且在您更新该变量后再次运行