axios拦截器中alert()弹出两次(Vue.js)

Alert() pops up twice in axios interceptor (Vue.js)

在我的 Vue 应用程序中,我实例化了一个 axios 实例,并在整个应用程序中使用它来处理 HTTP 请求。我已经设置了一个响应拦截器,它检查来自后端的任何响应是否为 401 unauthorized,如果是,则显示一条警告消息。此基本流程已实施,但您需要在警报消息上点击 "OK" 两次才能使其消失,我不确定为什么。

Axios 实例:

import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios';

const axiosInstance: AxiosInstance = axios.create();

axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => response,
  (error: AxiosError) => {
    if(error.response && error.response.status === 401) {
      alert('There has been an issue. Please log out and then log in again.');
      return Promise.reject(error);
    }
  }
);

export default axiosInstance;

响应被拦截的请求:

import axiosInstance from 'axios-instance';

  public async getloggedInUserId() {
    await axiosInstance.get('/sessions.json')
      .then((response) => {
        if(response.data.user_id) {
          this.SET_USER_ID(response.data.user_id);
        }
      });
  }

我已阅读此主题,但我的问题似乎有所不同:Javascript alert shows up twice

我尝试将 return 语句从 return Promise.reject(error); 更改为 return false;,但这对我没有任何帮助。

正如 Phil 在上面的评论中所建议的,查看浏览器控制台中的 Network 选项卡帮助我解决了这个问题。控制台显示了页面中的每个组件是如何加载的以及生成的响应代码。简而言之,实际上有两个进程返回 401,这就是 alert 被调用两次的原因。

我决定将调用 alert 的代码从全局 axios 拦截器(每当任何进程 returns 401 调用)移动到一个 .catch 块中特定的 axios 进程,因此它只被调用一次。

你的 promise 在 axios 错误拦截器中抛出错误,并在第二次调用时出错。