即使我从Vuex动作中的catch()收到错误,promise中的then()也会始终在Vue组件中执行

时间:2019-03-25 18:13:21

标签: vue.js graphql apollo

我正在使用apollo-vue graphql设置身份验证。在用户成功登录后将其重定向到主页。我从Vuex操作返回了promise,并在Vue组件中使用了then(),在该组件中,我将节点推入路由进行重定向,但是即使在Vue组件中的then()始终执行我从vuex动作中的catch()中收到错误,并且用户始终被重定向到首页

我已经尝试在Vue组件中的then()之后添加catch,它可以工作,但是我想在vuex中捕获我的错误,而不是在vue组件中

Vuex中的动作

login(){
 return apollo
  .mutate({
    mutation: CREATE_SHOP_USER,
    variables: signUpData
    })
   .then((res) => console.log(res))
   .catch((err) => console.log(err))
}

Vue组件中的方法

 userAuthenticate() {
      const userSignupData = {
        email: this.email,
        password: this.password
      };

      this.$store
        .dispatch("authenticateApp", userSignupData)
        .then(() => {
          this.$router.push("/");
        })        

我希望如果已经执行了Vuex动作中的catch,则不应执行Vue组件中的“ then”。

1 个答案:

答案 0 :(得分:2)

您可以将错误记录在vuex动作中,但是您需要再次抛出该错误,以使promise仍然被拒绝:

return apollo.mutate({
  mutation: CREATE_SHOP_USER,
  variables: signUpData
})
  .then((res) => console.log(res))
  .catch((err) => {
    console.log(err)
    throw err
  })

这将防止调用组件内部的then。当然,因为我们现在有了被拒绝的承诺,所以我们仍然应该处理被拒绝的情况:

this.$store
  .dispatch("authenticateApp", userSignupData)
  .then(() => {
    this.$router.push("/");
  })
  .catch(() => {
    // Handle rejection here
  })