programing

TypeError: 정의되지 않은 저장소 디스패치 vuex의 속성 'token'을 읽을 수 없습니다.

itsource 2022. 7. 5. 23:17
반응형

TypeError: 정의되지 않은 저장소 디스패치 vuex의 속성 'token'을 읽을 수 없습니다.

저는 Vuex 스토어를 사용하는 vue 컴포넌트를 가지고 있습니다.하지만 난...

TypeError: Cannot read property 'token' of undefined

에러. 왜 그런지 모르겠어.코드는 다음과 같습니다.

main.js:

import Vue from 'vue'
import Vuex from 'vuex';
import App from './App.vue'
import router from './router';
 import "./assets/css/tailwind.css";
import '@/assets/css/tailwind.css';
import store from './store';

Vue.config.productionTip = false;

 Vue.use(Vuex);

 
new Vue({
    router, store,
    render: h => h(App),
}).$mount('#app');

in store/indes.js:

import Vue from 'vue';
import Vuex from 'vuex';

 
Vue.use(Vuex);

export default new Vuex.Store({
    modules: {
    },
    state:  {
        token: ''
    }
})

Generic Form에서.vue:

  methods:  {
    execute()  {
      console.log("GenericForm.vue")

      if (this.inputFunction)  {
        this.inputFunction()
      }

      this.register()
    },

      register () {
      console.log("register()")
      try {
        const response =   AuthenticationService.register({
          email: 'testss',
          password: 'frgr'
        })
           this.$store.dispatch('setToken', response.data.token)
           this.$store.dispatch('setUser', response.data.user)
           this.$store.router.push({
          name: 'songs'
        })
      } catch (error) {
        console.log(error)
/*
        this.error = error.response.data.error
*/
      }
    }
  }

여기에 이미지 설명 입력

이 에러는, 다음의 코드 라인에서 발생합니다.

 this.$store.dispatch

어떤 도움이라도 감사합니다.

편집:

인증 서비스js

import api from './api'

export default  {
    register (credentials)  {
        return api().post('register', credentials)
    }
}

api.module

import axios from 'axios'

export default()  =>  {
    return axios.create({
        baseURL: 'http://localhost:8081'
    })
};

추가 후console.log다음과 같습니다.

편집 2:

새로운 방법:

    register: async () => {

     
      console.log("register()")
      const response = AuthenticationService.register({
        email: 'testss',
        password: 'frgr'
      }).then((response) => {

        console.log(response)
       /* this.$store.dispatch('setToken', response.data.token)
        this.$store.dispatch('setUser', response.data.user)*/
        this.$store.router.push({
          name: '/test'
        })
      });
    }

에러가 나다

 this.$store.router.push({
          name: '/test'
        })

행:

여기에 이미지 설명 입력

응답은 정상적으로 기록됩니다.

다음 두 가지 문제가 있습니다.

번째 문제:

다음 코드:

register(credentials)  {
    return api().post('register', credentials)
}

를 반환하고 있습니다.Promise(이것에는data소유물.당신이 원하는 것은 그 공리들에 접근해서response그 약속에 싸여있으니까, 넌 둘 중 하나야.

  • 불러then약속대로
AuthenticationService.register({...}).then((response) => {
    console.log(response.data.token) // 'foo'
});
  • 사용하다async/awaitVue 컴포넌트 내부

두 번째 문제

저장소가 정의되지 않는 원인은 화살표 함수를 사용하는 것입니다.register()메서드에는 화살표가 없어야 합니다.화살표가 삭제되면 오류는 발생하지 않습니다(스토어 및 라우터가 정의됩니다).

    async register() {
      console.log("register()")
      const response = AuthenticationService.register({
        email: 'testss',
        password: 'frgr'
      }).then((response) => {

        console.log(response)
        console.log(this.$store)
        this.$router.push({
          name: 'ha'
        })
      });
    }

즉, 이 명령어는data의 특성response정의되어 있지 않습니다.

이요?AuthenticationService.register메서드 비동기?

그런 것 같아요.이 경우 코드는 다음 시간 전에 계속됩니다.response개체가 올바르게 확인되었습니다.

잠깐 쉬었다가 달려라console.log(response)메서드가 비동기일 경우 해결되지 않은 약속이 표시될 수 있습니다.

그렇지 않으면 메서드가 아무것도 반환하지 않고 대신 콜백을 사용하는 경우 정의된 내용이 전혀 표시되지 않을 수 있습니다.

언급URL : https://stackoverflow.com/questions/67142028/typeerror-cannot-read-property-token-of-undefined-store-dispatch-vuex

반응형