【问题标题】:Access vuex store from catch block从 catch 块访问 vuex 存储
【发布时间】:2018-09-29 18:18:52
【问题描述】:

我试图将来自 api 调用的错误消息放入 vuex 存储中,但我不知道该怎么做。

我在 vue 文件中的“方法”中有这个

 axios
    .post("/api/model", this.model)
    .then(response => {
      window.location.href = "/Home/Index";
    })
    .catch(function(error) {
      if (error.response) {
        this.$store.commit("setServerErrors", error.response.data);
      }
    });

我收到以下错误: Uncaught (in promise) TypeError: Cannot read property '$store' of undefined

【问题讨论】:

  • 将函数更改为箭头,您将失去this 范围

标签: vue.js axios vuex


【解决方案1】:

可能您的函数正在重新分配 this 的值。

尝试将其更改为:

axios
    .post("/api/model", this.model)
    .then(response => {
      window.location.href = "/Home/Index";
    })
    .catch(error => {  // <= HERE IS THE CHANGE!!
      if (error.response) {
        this.$store.commit("setServerErrors", error.response.data);
      }
    });

在此处了解function(arg) {}和(arg) =&gt; {}之间的区别:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

【讨论】:

    【解决方案2】:

    您在 catch 块上使用函数而不是箭头函数,因此该块内的 this 具有不同的范围。

    只需将函数替换为箭头函数即可。

    axios
        .post("/api/model", this.model)
        .then(response => {
          window.location.href = "/Home/Index";
        })
        .catch((error) => {
          if (error.response) {
            this.$store.commit("setServerErrors", error.response.data);
          }
        });
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2018-07-06
      • 2021-07-22
      • 2018-11-10
      • 1970-01-01
      • 2019-03-22
      • 2017-12-05
      • 2018-12-08
      • 2021-08-30
      相关资源
      最近更新 更多