여씨의 개발이야기

[Vue] Cannot read properties of undefined (reading '$router') 본문

🐞 Debug

[Vue] Cannot read properties of undefined (reading '$router')

yeossi 2022. 1. 24. 18:01

📢 이 버그 좀 보세요!

let self = this;
axios.post(process.env.xxxxx + '/user/update/adminPortal', self.xxxx)
    .then(function (res) {
        this.getData();
        this.$router.push("/userList");
        //$("#updateModal").modal('hide');
    })
    .catch(function (error) {
        console.log('Submit Failed', error)
    })

위와 같이 axios.post 내에서 router.push를 하면 Cannot read properties of undefined (reading '$router') 에러가 뜬다.

🐞 버그가 나타난 이유?

참조 : https://stackoverflow.com/questions/57020098/vue-js-typeerror-cannot-read-property-router-of-undefined

 

Vue.js: TypeError: Cannot read property '$router' of undefined?

Laravel 5.7 and Vue.js2. I am working with JWT Authentication and Vuex to store my LoggedIn User information. When I want to redirect to homepage after login $router is giving this unexpected error.

stackoverflow.com

You use this code: this.$router.push({path: '/'}); in Function context. U can read more about "this" in javascript there https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

To correct the error, write the following code:

login()
{
        let self = this;
        Axios.post('/api/auth/login',{
          email: this.form.email,
          password: this.form.password
        })
        .then(function(response){

          let token = response.data.access_token;
          let username = response.data.user.name;
          let role = response.data.user.role;

          if(Token.isValid(token))
          {
            localStorage.setItem('token', token);
            localStorage.setItem('username', username);
            localStorage.setItem('role', role);

            self.$router.push({path: '/'});
          }

        })
        .catch(function(error){
          console.log(error)
        })
}

I have put "this" higher in context. Or u can use arrow function:

login()
{
        Axios.post('/api/auth/login',{
          email: this.form.email,
          password: this.form.password
        })
        .then((response) => {

          let token = response.data.access_token;
          let username = response.data.user.name;
          let role = response.data.user.role;

          if(Token.isValid(token))
          {
            localStorage.setItem('token', token);
            localStorage.setItem('username', username);
            localStorage.setItem('role', role);

            this.$router.push({path: '/'});
          }

        })
        .catch(function(error){
          console.log(error)
        })
}

u can read about arrow functions there: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

🕸 어떻게 이 버그를 잡을까?

this -> self 로 바꿔준다. 또는 .then 구문에 arrow를 사용해준다.

Comments