You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用async/await时检测axios请求的加载状态以禁用按钮

实现方案

你可以通过维护一个加载状态变量来控制按钮的禁用状态,具体实现步骤如下:

1. 定义加载状态

根据你使用的环境(原生JS/React/Vue等),声明一个状态变量(比如isLoading),初始值设为false。

2. 请求前后更新状态

在发起axios请求前将isLoading设为true,触发按钮禁用;请求完成(无论成功或失败)后,再把isLoading设回false,恢复按钮可用。

原生JS示例

let isLoading = false;
const requestButton = document.getElementById("request-btn");

async function fetchData() {
  isLoading = true;
  requestButton.disabled = isLoading;
  
  try {
    const response = await API.get("/url", options);
    // 处理响应数据
  } catch (error) {
    // 处理请求错误
  } finally {
    isLoading = false;
    requestButton.disabled = isLoading;
  }
}

requestButton.addEventListener("click", fetchData);

React示例

import { useState } from 'react';

function RequestComponent() {
  const [isLoading, setIsLoading] = useState(false);

  async function fetchData() {
    setIsLoading(true);
    try {
      const response = await API.get("/url", options);
      // 处理响应数据
    } catch (err) {
      // 处理请求错误
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <button 
      onClick={fetchData} 
      disabled={isLoading}
    >
      {isLoading ? "加载中..." : "发起请求"}
    </button>
  );
}

Vue示例

<template>
  <button 
    @click="fetchData" 
    :disabled="isLoading"
  >
    {{ isLoading ? '加载中...' : '发起请求' }}
  </button>
</template>

<script setup>
import { ref } from 'vue';
const isLoading = ref(false);

async function fetchData() {
  isLoading.value = true;
  try {
    const response = await API.get("/url", options);
    // 处理响应数据
  } catch (err) {
    // 处理请求错误
  } finally {
    isLoading.value = false;
  }
}
</script>

关键提示

  • 必须用finally块重置isLoading,确保请求无论成功或失败,按钮都能恢复可用,避免出现按钮永久禁用的问题。
  • 框架环境下(React/Vue),状态更新会自动同步UI;原生JS则需要手动更新按钮的disabled属性。

内容的提问来源于stack exchange,提问作者Zain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:31:04