首页 > 解决方案 > Vuex-module-decorator,修改动作内部的状态

问题描述

使用vuex-module-decorator我有一个authenticate动作应该改变状态。

@Action
public authenticate(email: string, password: string): Promise<Principal> {
    this.principal = null;
    return authenticator
      .authenticate(email, password)
      .then(auth => {
          const principal = new Principal(auth.username);
          this.context.commit('setPrincipal', principal);
          return principal;
      })
      .catch(error => {
          this.context.commit('setError', error);
          return error;
      });
}

// mutations for error and principal

但这失败并显示以下消息:

未处理的承诺拒绝错误:“ERR_ACTION_ACCESS_UNDEFINED:您是否尝试在 @Action 中访问 this.someMutation() 或 this.someGetter?这仅适用于动态模块。如果不是动态的,请使用 this.context.commit("mutationName", payload)和 this.context.getters["getterName"]

我不明白的是它与@MutationActionand配合得很好async。但是我想念返回类型Promise<Principal>

@MutationAction
public async authenticate(email: string, password: string) {
    this.principal = null;
    try {
        const auth = await authenticator.authenticate(email, password);
        return { principal: new Principal(auth.username), error: null };
    } catch (ex) {
        const error = ex as Error;
        return { principal: null, error };
    }
}

--

此时我感到受阻,并希望得到一些帮助来实现@Action可以改变状态并在 a 中返回特定类型的 a Promise

标签: vue.jsvuexvuex-modules

解决方案


只需将 rawError 选项添加到注释中即可

   @Action({rawError: true})

并且正常显示错误。这是因为库“vuex-module-decorators”包装错误,因此通过这样做,您将能够获得可以使用的 RawError


推荐阅读