When using Axios for AJAX requests, you may encounter situations where multiple duplicate requests are sent simultaneously. This typically occurs when users accidentally click a button multiple times or when the application re-triggers requests due to unhandled state updates. To avoid this, you can adopt the following strategies:
1. Using Flag Variables or State
javascriptlet isRequesting = false; function fetchData() { if (isRequesting) { return; // If a request is already in progress, return immediately to avoid duplicate requests } isRequesting = true; axios.get('/api/data') .then(response => { // Handle response data }) .catch(error => { // Handle errors }) .finally(() => { isRequesting = false; // Request ends, clear the flag regardless of success or failure }); }
2. Using Cancel Token
javascriptconst CancelToken = axios.CancelToken; let cancel; function fetchData() { if (cancel) { cancel(); // Cancel the previous request } axios.get('/api/data', { cancelToken: new CancelToken(function executor(c) { cancel = c; }) }) .then(response => { // Handle response data }) .catch(error => { if (axios.isCancel(error)) { console.log('Request canceled', error.message); } else { // Handle other errors } }) .finally(() => { cancel = null; // Clear the cancel function after completion }); }
3. Debounce or Throttle
javascriptimport _ from 'lodash'; const fetchDataDebounced = _.debounce(() => { axios.get('/api/data') .then(response => { // Handle response data }) .catch(error => { // Handle errors }); }, 300); // Event handler function function handleButtonClick() { fetchDataDebounced(); }
By using one or a combination of these strategies, you can effectively prevent sending multiple duplicate AJAX requests when using Axios.
2024年6月29日 12:07 回复