如何在使用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
相关产品推荐
相关产品推荐

