我如何修复 VueJS 中的“this is undefined”?

How can i fix “this is undefined” in VueJS?

this.$store.commit('disconnect'); 导致“这是未定义的”错误,我该怎么办?

store/index.js :

export const state = () => ({
  log: false,
  user: {token: null, id: null, username: null, email: null, created_at: null, pseudo: null}
})


export const mutations = {
  connect (state) {
    state.log = true
  },
  disconnect (state) {
    state.log = false,
    state.user.id = null,
    state.user.username = null,
    state.user.email = null,
    state.user.created_at = null,
    state.user.pseudo = null
  }
}

index.vue

<script>
import axios from "axios";

  methods: {
    async login() {
    var self = this;

    const auth_res = axios({
      method:'post',
      url:'http://127.0.0.1:8000/v2.0/auth',
      data:{
        username: this.username,
        password: this.password
      }
      }).then(function(res){
        this.$store.commit('disconnect');
        self.$router.push('/');
      }).catch(function (erreur) {
        console.log(erreur);
      });
    }
  }
}
</script>

如果我删除 index.vue 文件中的 commit 行,它工作正常,但我需要使用它,所以我该如何解决这个问题?

再次感谢

在回调上下文中,this 紧张回调本身。这就是你收到错误的原因。您应该将其替换为,

self.$store.commit('disconnect');

其中 self 包含 Vue 的实际上下文。这是解释,

methods: {
    async login() {
    var self = this; // You got the context of the method which belongs to Vue

    const auth_res = axios({
      method:'post',
      ...
      }).then(function(res){
        self.$store.commit('disconnect'); // The self.$store is now avaialable in callback
        self.$router.push('/');
      }).catch(function (erreur) {
        ...
      });
    }
  }