axios发布请求后的vue-router推送路由

问题描述

当我编写以下代码时:

axios.post('/user',{ email: this.email })
.then(
    (response) => {
      if (!response.data) {
        this.$router.push({ path: '/register',params: { user: defaultUser } });
      } else {
        this.$router.push({ path: '/login',params: { user: response.data } });
      }
    },(error) => {
      console.log(error);
    }
);

编译器显示错误@typescript-eslint/no-floating-promises: Promises must be handled appropriately or explicitly marked as ignored with the void operator.

我还尝试在catch块之后放置catch块,但这仍然是相同的问题。

axios.post('/user',{ email: this.email })
  .then((response) => {
    if (!response.data) {
      this.$router.push({ path: '/register',params: { user: defaultUser } });
    } else {
      this.$router.push({ path: '/login',params: { user: response.data } });
    }
  })
  .catch((error) => {
    console.log(error);
  });

我还发现当我注释掉this.$router.push时,问题消失了。因此,问题可能在于重定向路线和解决承诺。也许最好将问题改写为“ 如何重定向路由而不留下未解决的诺言”?我希望我把问题弄清楚。

解决方法

好,终于我明白了。 this.$router.push()返回的诺言我没有很好地处理。最终的解决方案如下:

axios.post('/user',{ email: this.email })
  .then((response) => {
    if (!response.data) {
      void this.$router.push({ path: '/register',params: { user: defaultUser } });
    } else {
      void this.$router.push({ path: '/login',params: { user: response.data } });
    }
  })
  .catch((error) => {
    console.log(error);
  });

由于拥有void会触发eslint no-void语法错误,并且我不在乎此promise的返回值,因此我通过添加/* eslint-disable no-void */来抑制警告。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...