Search code examples
javascriptvue.jsvuex

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


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


Solution

  • 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!')
        })
    }