umi max請(qǐng)求攔截器重復(fù)進(jìn)入問題

1、問題描述

直接為umi的request方法配置攔截器,當(dāng)多條請(qǐng)求同時(shí)觸發(fā)時(shí),發(fā)現(xiàn)同一個(gè)請(qǐng)求會(huì)觸發(fā)攔截器代碼多次執(zhí)行。

import { request?} from '@umijs/max';

export const requestOrigin = (url, opts) => {

? return request(url, {

? ? ?//?umi中的request對(duì)攔截器注入實(shí)現(xiàn)有bug, 多個(gè)接口同時(shí)并發(fā)的情況下會(huì)導(dǎo)致攔截函數(shù)被多次執(zhí)行

? ?? ?requestInterceptors: [requestInterceptor1, requestInterceptor2, requestInterceptor3],

? ? ? responseInterceptors: [responseInterceptor1, responseInterceptor2],

? ? ? ...opts,

? }).then(() => {

? ? // xxx

? }).catch(() => {

? ? // xxx

? });

}


2、解決方案

改用 injectInterceptors() 進(jìn)行攔截器注入。

import {?request?} from '@umijs/max';

export const requestOrigin = (url, opts) => {

? ? injectInterceptors();

? ? return?request(url, {

? ? ? ? ...opts,

? ? ?}).then(() => {

? ? ? ?// xxx

? ? ?}).catch(() => {

? ? ? ?// xxx

? ? ? });

}

injectInterceptors實(shí)現(xiàn)如下:

import { getRequestInstance } from '@umijs/max';

import isArray from 'lodash-es/isArray';

// 注入標(biāo)志器,保證全局僅注入一次

let hasInject = false;

// 請(qǐng)求攔截器

const requestInterceptors = [requestInterceptor1,?requestInterceptor2,?requestInterceptor3];

// 返回?cái)r截器

const responseInterceptors = [responseInterceptor1,?responseInterceptor2];

export function injectInterceptors() {

? if (!hasInject) {

? ? const requestInstance = getRequestInstance();

? ? requestInterceptors.forEach((interceptor: any) => {

? ? ? if (isArray(interceptor)) {

? ? ? ? requestInstance.interceptors.request.use((config) => {

? ? ? ? ? const { url } = config;

? ? ? ? ? if (interceptor[0].length === 2) {

? ? ? ? ? ? const { url: newUrl, options } = interceptor[0](url, config);

? ? ? ? ? ? return { ...options, url: newUrl };

? ? ? ? ? }

? ? ? ? ? return interceptor[0](config);

? ? ? ? }, interceptor[1]);

? ? ? } else {

? ? ? ? requestInstance.interceptors.request.use((config) => {

? ? ? ? ? const { url } = config;

? ? ? ? ? if (interceptor.length === 2) {

? ? ? ? ? ? const { url: newUrl, options } = interceptor(url as string, config) as any;

? ? ? ? ? ? return { ...options, url: newUrl };

? ? ? ? ? }

? ? ? ? ? return interceptor(config);

? ? ? ? });

? ? ? }

? ? });

? ? responseInterceptors.forEach((interceptor) => {

? ? ? isArray(interceptor)

? ? ? ? ? requestInstance.interceptors.response.use(interceptor[0], interceptor[1])

? ? ? ? : requestInstance.interceptors.response.use(interceptor);

? ? });

? }

? hasInject = true;

}

export default injectInterceptors;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容