Uncaught TypeError: Cannot read property '$store' of null

元气小坏坏 提交于 2020-08-09 07:18:09

问题


I'm just a newbie to programming and have just tried Vue for few days.

Here I would like to store user's geolocation data to Vuex state by the following code.

    mounted () {
    navigator.geolocation.getCurrentPosition(foundLocation, noLocation)
    function foundLocation (position) {
      var userLoc = {
        Lon: position.coords.longitude,
        Lat: position.coords.latitude
      }
      console.log(userLoc)
      this.$store.dispatch('userLocSave', {lat: userLoc.Lat, lon: userLoc.Lon})
    }
    function noLocation () {
      console.log('No Location found!')
    }
  }

and here's code in store.js State

  state: {
    userLat: null,
    userLon: null
  }

Mutation

userLocation (state, locData) {
  state.userLat = locData.lat
  state.userLon = locData.lon
}

Action

userLocSave ({commit}, locData) {
  commit('userLocation', {
    lat: locData.lat,
    lon: locData.lon
  })
}

However, it doesn't work as I thought and shows this error.

Uncaught TypeError: Cannot read property '$store' of null
at foundLocation

I have tried to search, but have no idea what keywords, and I have been stuck with this problem for a day already. So, I decided to ask here. Thank you


回答1:


This is an issue with scope:

this in the context your using it is scoped to your function() not the vue instance.

One way to sort this would be to use arrow functions. Arrow functions maintain the scope of the caller so in this instance, this will still be scoped to the vue instance.

mounted () {
    navigator.geolocation.getCurrentPosition(
    () => {
        var userLoc = {
            Lon: position.coords.longitude,
            Lat: position.coords.latitude
        }
        console.log(userLoc)
        this.$store.dispatch('userLocSave', {lat: userLoc.Lat, lon: userLoc.Lon})
    }, 
    () => { 
        console.log('No Location found!')
    })
}


来源:https://stackoverflow.com/questions/48472221/uncaught-typeerror-cannot-read-property-store-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!