vue3中action添加请求报错,导致axios响应拦截器捕获异常,所以请求接口都无法发出去

发布于 2022-09-13 00:20:30 字数 5775 浏览 35 评论 0

user.ts

import {
  ActionContext,
  ActionTree,
  // GetterTree,
  MutationTree,
  Module,
  Store as VuexStore,
  CommitOptions,
  DispatchOptions,
  GetterTree,
} from 'vuex'
import { State as RootState } from '@/store'
import { UserInfo } from './../../interface/user';
import { getUserInfo } from '@/api/user/user';


export type State = {
  userInfo: UserInfo | null;
  loginToken: string;
}
const state: State = {
  userInfo: null,
  loginToken: "",
}

export type Mutations<S = State> = {
  setUserInfo(state: S, userInfo: UserInfo): void;
  delUserInfo(state: S): void;
  setLoginToken(state: S, loginToken: string): void;
  delLoginToken(state: State): void;
}
const mutations: MutationTree<State> & Mutations = {
  //保存用户信息
  setUserInfo(state: State, userInfo: UserInfo) {
    state.userInfo = userInfo;
  },
  delUserInfo(state: State) {
    state.userInfo = null;
  },
  //保存登陆token
  setLoginToken(state: State, loginToken: string) {
    state.loginToken = loginToken;
  },
  delLoginToken(state: State) {
    state.loginToken = '';
    localStorage.setItem('loginToken', '');
  }
}


type AugmentedActionContext = {
  commit<K extends keyof Mutations>(
    key: K,
    payload: Parameters<Mutations[K]>[1],
  ): ReturnType<Mutations[K]>;
} & Omit<ActionContext<State, RootState>, 'commit'>
export interface Actions {
  updateUserInfo(
    { commit }: AugmentedActionContext,
    token: string,
  ): void;
}

// Define actions
export const actions: ActionTree<State, RootState> & Actions = {
  //更新用户信息
  updateUserInfo(
    { commit },
    token: string,
  ) {
    // try {
    function a() {
      getUserInfo(token)
    }
    // } catch (err) {
    // console.log(err)
    // }
  },
}

// getters types
export type Getters = {
  getToken(state: State): string | null;
}

// getters
export const getters: GetterTree<State, RootState> & Getters = {
  getToken: (state: State) => {
    return state.loginToken || localStorage.getItem('logonToken');
  },
}

export type Store<S = State> = Omit<
  VuexStore<S>,
  'commit' | 'getters' | 'dispatch'
> & {
  commit<K extends keyof Mutations, P extends Parameters<Mutations[K]>[1]>(
    key: K,
    payload: P,
    options?: CommitOptions,
  ): ReturnType<Mutations[K]>;
} & {
  getters: {
    [K in keyof Getters]: ReturnType<Getters[K]>
  };
} & {
  dispatch<K extends keyof Actions>(
    key: K,
    payload: Parameters<Actions[K]>[1],
    options?: DispatchOptions,
  ): ReturnType<Actions[K]>;
}

export const UserModule: Module<State, RootState> = {
  state,
  mutations,
  actions,
  // getters,
}

请求方法

import { HttpService } from "@/until/http.service";
import { UrlService } from "../url.base";
import { UserInfo } from "@/interface/user";
import { RootObject } from "@/interface/rootInterface";

//登陆
export const loginUser = (token: string): Promise<RootObject<UserInfo>> => {
  return HttpService.post<RootObject<UserInfo>>(UrlService.login, { token })
}

export const getUserInfo = (token: string): Promise<RootObject<UserInfo>> => {
  return HttpService.get<RootObject<UserInfo>>(UrlService.getUserInfo, { token })
}

httpservice

/*
 * @Date: 2021-05-19 11:27:58
 * @LastEditors: wanting
 * @LastEditTime: 2021-05-19 15:29:48
 * @FilePath: /src/service/http.service.ts
 */
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { useStore } from "@/store";
import qs from "qs";

axios.defaults.withCredentials = true;//允许带cookie
const store = useStore();
// 请求拦截器
axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (store.state.user.loginToken) {
      config.headers.ACCESS_TOKEN = store.state.user.loginToken;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截器
axios.interceptors.response.use((response: AxiosResponse) => {
  if (response.status === 200) {
    return Promise.resolve(response.data);
  } else {
    return Promise.reject(response);
  }
},
  (error: unknown) => {
    Promise.reject(JSON.stringify(error));
  }
);

export class HttpService {

  /**
   * 
   * @param url 请求url
   * @param params 请求参数
   * @returns 返回Promise<R> R返回类型
   */
  public static get<R = AxiosResponse>(
    url: string,
    params?: unknown
  ): Promise<R> {
    return axios.request({
      url,
      method: "get",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
      timeout: 5000,
      withCredentials: true,
      params,
    });
  }

  /**
   * 
   * @param url 请求url
   * @param params 请求参数
   * @returns 返回Promise<R> R返回类型
   */
  public static post<R = AxiosResponse>(
    url: string,
    params: any
  ): Promise<R> {
    return axios.post(url, qs.stringify(params), {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      }
    });
  }

  /**
   * //并发请求
   * @param axiosArr 所并发的请求
   * @returns reasult[]
   */
  public static httpAll<T>(axiosArr: Promise<T>[]): Promise<T[]> {
    return new Promise((resovle) => {
      axios.all(axiosArr).then(axios.spread((...args: T[]) => {
        resovle(args)
      }))
    })
  }

}

store action 中添加getUserInfo请求就导致页面其它所有请求都报错了(getUserInfo别的请求也一样,注释那一行就好了)
我把getUserInfo放在一个函数中都会报错(这个函数都还没执行呢)
是我的写法有问题吗?
文件如下

报错如下

即htppsevice中拦截器捕获异常了

是我哪里写的有问题吗

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七分※倦醒 2022-09-20 00:20:30

自己sb了,找到问题了,问题是httpservice文件引用了store,store中又添加了getUserInfo请求,也就是间接引用了httpservice,彼此引用彼此了

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文