首页首页
前端
非前端
辅助
Github
前端
非前端
辅助
Github
  • 前端基础

    • HTML基础
    • CSS基础
    • JS基础
    • ES6基础
    • HTTP基础
    • 前端缓存
    • 页面性能
    • 数据结构基础
    • 我的文章
  • 前端进阶

    • Vue2基础
    • Vue2进阶
    • Vue3基础
    • Vue3进阶
    • React基础
    • React进阶
    • React18新特性
    • Vue和React对比
    • RN基础
    • RN环境搭建和打包发布
    • 打包工具
    • TS基础
    • Nuxt基础
    • 小程序基础
    • 微前端基础
    • uni-app基础
    • 业务相关
    • 低代码相关
  • 前端代码练习

    • CSS代码练习
    • JS代码练习
    • 算法代码练习
  • 前端代码技巧

    • 工具库
    • 工具函数
    • CSS动画库
    • CSS代码技巧
    • JS代码技巧
    • 项目技巧

1、项目踩坑

1、华为荣耀 自带浏览器 position:fixed 底部被工具栏遮挡 解决办法

head中添加

<meta name="x5-fullscreen" content="true">

2、vue数据变化,视图层没变化, 数据强制更新

this.$forceUpdate()

2、Axios怎么撤回一个请求

一、使用 CancelToken (Axios < 0.22.0)

基本用法

import axios from 'axios';

// 1. 创建取消令牌源
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
// 2. 发起请求
axios.get('/api/data', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('请求已取消', thrown.message);
  } else {
    // 处理其他错误
  }
});
// 3. 取消请求
source.cancel('用户主动取消操作');

完整示例

let cancel;
axios.get('/user', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个取消函数作为参数
    cancel = c;
  })
});
// 取消请求
cancel();

二、使用 AbortController (Axios ≥ 0.22.0)

现代浏览器和 Node.js(v15+)支持的标准方法:

const controller = new AbortController();

axios.get('/api/data', {
  signal: controller.signal
}).catch(function (error) {
  if (error.name === 'CanceledError') {
    console.log('请求已取消');
  }
});

// 取消请求
controller.abort();

三、最佳实践

请求拦截器中统一处理

// 存储所有活动的控制器
const activeRequests = new Map();

axios.interceptors.request.use(config => {
  const requestId = `${config.method}-${config.url}`;
  
  // 如果已有相同请求,取消前一个
  if (activeRequests.has(requestId)) {
    activeRequests.get(requestId).abort();
  }
  
  const controller = new AbortController();
  config.signal = controller.signal;
  activeRequests.set(requestId, controller);
  
  return config;
});

axios.interceptors.response.use(response => {
  const requestId = `${response.config.method}-${response.config.url}`;
  activeRequests.delete(requestId);
  return response;
}, error => {
  if (error.config) {
    const requestId = `${error.config.method}-${error.config.url}`;
    activeRequests.delete(requestId);
  }
  return Promise.reject(error);
});
最后更新: 2025/5/29 10:26
Prev
JS代码技巧