You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue使用Vuex存储地理位置时遇Uncaught TypeError错误求助

解决Vue中访问$store时的TypeError问题

嘿,别着急,这个问题其实挺常见的,我来帮你拆解一下!

问题根源

你遇到的Uncaught TypeError: Cannot read property '$store' of null错误,核心原因是**foundLocation函数里的this指向不对**。

当navigator.geolocation.getCurrentPosition调用你的回调函数foundLocation时,这个普通函数的this上下文并不是Vue组件实例,而是变成了null(严格模式下),自然就找不到$store了。

几种解决方案

这里给你三种简单有效的修复方式,选哪种都可以:

方案1:使用箭头函数(最推荐)

箭头函数不会创建自己的this,它会继承外层作用域的this(也就是Vue组件实例),这样就能正常访问$store了:

mounted () {
  navigator.geolocation.getCurrentPosition((position) => {
    const 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!')
  })
}

方案2:把函数放到methods中

Vue的methods里的函数会自动绑定组件实例的this,你可以把两个回调函数移到methods里:

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

方案3:手动绑定this

如果你想保留原来的函数写法,可以用bind()把组件实例的this绑定到函数上:

mounted () {
  // 提前绑定this到foundLocation函数
  navigator.geolocation.getCurrentPosition(foundLocation.bind(this), noLocation)
  
  function foundLocation (position) {
    const 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!')
  }
}

额外检查

顺便看了下你的Vuex代码,State、Mutation和Action的逻辑都是对的,只要修复了this的问题,就能正常把地理位置数据存入Vuex状态了。

另外测试的时候记得允许浏览器获取你的地理位置权限哦,不然会触发noLocation回调~

内容的提问来源于stack exchange,提问作者spnj2000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:38:47