A
A
Andrey2020-05-25 16:50:30
Vue.js
Andrey, 2020-05-25 16:50:30

Vuex. Why won't action be executed?

I'm trying to implement JWT by examples. When the "Logout" button is clicked, the "Logout" method will be executed.

methods: {
      logout: function () {
        this.$store.dispatch('logout').then(() => {
          this.$router.push('/login')
        })
      }
    },

But if the server returned 401, I try to log out the user in the same way, I get an error
TypeError: this is undefined
at the place where "Logout" was called.
created() {
      this.$http.interceptors.response.use(undefined, function (error) {
        return new Promise(function () {
          if (error.response.status === 401 && error.config && !error.config.__isRetryRequest) {
            console.log('test')
            this.$store.dispatch('logout')  <-- вот тут получаю ошибку
          }
          throw error;
        });
      });
    }

The condition will be fulfilled because I see the message "test". I noticed that if you put it right after created, then it will be executed. I can't figure out what the problem is. this.$store.dispatch('logout')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2020-05-25
@DronTat

Because function is used in the promise and above, replace it with a lambda, then the context will be saved:

created() {
      this.$http.interceptors.response.use(undefined, (error) => {
        return new Promise(() => {
          if (error.response.status === 401 && error.config && !error.config.__isRetryRequest) {
            console.log('test')
            this.$store.dispatch('logout')  <-- вот тут получаю ошибку
          }
          throw error;
        });
      });
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question