LoginSignup
64
39

More than 5 years have passed since last update.

Vue.jsのdataオブジェクトを参照する際に Uncaught (in promise) TypeError: Cannot set property 'foo' of undefined

Posted at

Promiseパターンで返ってくる値を、dataオブジェクトのfooにセットします。

export default {
  name: 'foo',
  data() {
    return {
      foo: ''
    }
  }
...
Promise-pattern(Before)
getData: function() {
  this.$firestore.collection('posts').where('categories.cat', '==', true)
    .get()
    .then(function(querySnapshot) {
      let data = []
      querySnapshot.forEach(function(doc) {
        data.push(doc.data())
      })
      this.foo = data
    })

Uncaught (in promise) TypeError: Cannot set property 'foo' of undefined

undefinedfooには何もセットできんぞ!!」と怒られてしまいます。

解決策: thisへのreference用変数(self)をつくる

Promise-pattern(After)
getData: function() {
  let self = this
  this.$firestore.collection('posts').where('categories.cat', '==', true)
    .get()
    .then(function(querySnapshot) {
      let data = []
      querySnapshot.forEach(function(doc) {
        data.push(doc.data())
      })
      self.foo = data
    })

無事、dataオブジェクトのfooに対して返り値をセットすることができました。:tada:
thisや変数のscope範囲を理解していないとハマります...。

参考リンク

64
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
64
39