source

수집되지 않은 유형 오류: null의 속성 '$store'를 읽을 수 없습니다.

bestscript 2023. 1. 16. 20:07

수집되지 않은 유형 오류: null의 속성 '$store'를 읽을 수 없습니다.

저는 프로그래밍을 처음 하는 사람이고 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!')
    }
  }

여기에 코드가 있습니다.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 인스턴스가 아닙니다.

이를 정렬하는 한 가지 방법은 화살표 기능을 사용하는 것입니다.화살표 함수는 발신자의 범위를 유지하기 위해 이 경우,thisvue 인스턴스로 계속 범위가 지정됩니다.

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

언급URL : https://stackoverflow.com/questions/48472221/uncaught-typeerror-cannot-read-property-store-of-null