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

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

我只是一个编程新手,刚刚试用了 Vue 几天。

这里我想通过以下代码将用户的地理位置数据存储到Vuex状态。

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

这是 store.js 中的代码

  state: {
    userLat: null,
    userLon: null
  }

变异

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

动作

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

然而,它并没有像我想的那样工作,并显示了这个错误。

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

我试过搜索,但不知道是什么关键字,我已经被这个问题困了一天了。所以,我决定在这里问一下。谢谢

这是范围问题:

this 在上下文中你使用它的范围是你的 function() 而不是 vue 实例。

排序的一种方法是使用 arrow functions。箭头函数维护调用者的作用域,因此在这种情况下,this 仍将作用于 vue 实例。

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