惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
Y
Y Combinator Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
S
SegmentFault 最新的问题
J
Java Code Geeks
V
Visual Studio Blog
H
Help Net Security
Stack Overflow Blog
Stack Overflow Blog
aimingoo的专栏
aimingoo的专栏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Tailwind CSS Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
H
Hackread – Cybersecurity News, Data Breaches, AI and More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - Franky
B
Blog RSS Feed
The Cloudflare Blog
MyScale Blog
MyScale Blog
月光博客
月光博客
Microsoft Security Blog
Microsoft Security Blog
美团技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Stop Race Conditions: React AbortControllers ⚡
Prajapati Paresh · 2026-06-21 · via DEV Community
Cover image for Stop Race Conditions: React AbortControllers ⚡

Prajapati Paresh

The Unmounted Component Trap

In highly interactive dashboards at Smart Tech Devs, users navigate quickly. Imagine a user clicks a "Generate Heavy Report" button, which fires an API request that takes 4 seconds to resolve. After 2 seconds, the user gets bored, clicks the "Back" button, and navigates away. The React component unmounts.

However, the browser's HTTP request is still in-flight! Two seconds later, the promise resolves, and the callback attempts to execute setReportData(data) on a component that no longer exists. This triggers the infamous React memory leak warning: "Can't perform a React state update on an unmounted component."

The Data Fetching Race Condition

An even worse bug occurs in search bars. A user types "A" (Request 1 fires, takes 3s). The user types "B" (Request 2 fires, takes 1s). Request 2 resolves first, showing the correct results for "AB". But two seconds later, the slow Request 1 finally resolves, overwriting the screen with the outdated results for just "A". To solve both memory leaks and race conditions, you must cancel stale API requests using the AbortController.

Architecting Cancellable Requests

The native Web AbortController API allows us to cleanly sever the connection to an active HTTP fetch request the moment a component unmounts or a dependency changes.


// components/dashboard/LiveSearch.tsx
"use client";

import React, { useState, useEffect } from 'react';

export default function LiveSearch() {
    const [query, setQuery] = useState('');
    const [results, setResults] = useState([]);

    useEffect(() => {
        if (!query) return;

        // 1. Initialize the AbortController
        const controller = new AbortController();
        const signal = controller.signal;

        const fetchData = async () => {
            try {
                // 2. Pass the signal to the fetch request
                const response = await fetch(`/api/search?q=${query}`, { signal });
                const data = await response.json();
                setResults(data);
            } catch (error: any) {
                // 3. Gracefully ignore AbortErrors (these are intentional cancellations)
                if (error.name === 'AbortError') {
                    console.log('Stale request cancelled.');
                } else {
                    console.error('Fetch error:', error);
                }
            }
        };

        fetchData();

        // 4. CLEANUP: When the component unmounts OR the query changes before 
        // the previous fetch completes, instantly kill the old network request!
        return () => {
            controller.abort();
        };
    }, [query]); // Re-runs on every keystroke

    return (
        <div className="p-6 bg-white border rounded-xl">
            <input 
                type="text" 
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Search database..."
                className="w-full p-2 border rounded"
            />
            {/* Render results... */}
        </div>
    );
}

The Engineering ROI

Implementing AbortController ensures your client-side architecture remains perfectly deterministic. You immediately free up browser network connections by killing abandoned requests, completely eliminate the risk of out-of-order race conditions in search inputs, and keep your React application free of memory leaks and unmounted state warnings.