-1

当我编写以下代码时:

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.

我也尝试在 then 块之后放置一个 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。所以问题可能涉及重定向路由和解决承诺。也许最好将问题重新表述为“如何在不留下未解决的承诺的情况下重定向路线”?我希望我把问题说清楚。

4

1 回答 1

0

好的,我终于想通了。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);
  });

因为 havevoid会触发eslint no-void语法错误,而且我不关心这个 promise 的返回值,所以我通过添加/* eslint-disable no-void */.

于 2020-08-23T19:19:51.320 回答