React Native fetch API异常:页面持续刷新,安卓模拟器加载停滞求助
Hey there! Let's figure out why your Android app's fetch API call is stuck on loading and causing endless page refreshes—these are super common issues, but we can work through them step by step.
1. Infinite Refresh Caused by Unhandled Promises
If your fetch call is placed directly in a component's render cycle (like a React component without a dependency array in useEffect, or a WebView's page load callback), every time the data returns (even on failure), it triggers a re-render—which then re-runs the fetch call, creating a loop.
Example of incorrect code:
// Bad example in a React component function DataScreen() { const [data, setData] = useState(null); // Runs every time the component re-renders, no stop condition fetch('https://your-api-url.com/data') .then(res => res.json()) .then(data => setData(data)) .catch(err => console.error(err)); return <div>{data ? JSON.stringify(data) : "Loading..."}</div>; }
Fix: Use useEffect with an empty dependency array to run the fetch only once on mount; add dependencies if you need to re-fetch when certain values change:
function DataScreen() { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { try { const res = await fetch('https://your-api-url.com/data'); const result = await res.json(); setData(result); } catch (err) { console.error('Fetch failed:', err); } }; fetchData(); }, []); // Empty array = runs only on component mount return <div>{data ? JSON.stringify(data) : "Loading..."}</div>; }
2. Loading State Never Ends Due to Unhandled Errors
If your fetch request fails (network issues, API returns 404/500), but you don't update the loading state in the catch block, the page stays stuck on "Loading". Worse, if the error triggers a re-render, it can start a refresh loop.
Add loading and error states to handle this properly:
function DataScreen() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { setLoading(true); const res = await fetch('https://your-api-url.com/data'); if (!res.ok) { throw new Error(`HTTP Error! Status: ${res.status}`); } const result = await res.json(); setData(result); setError(null); } catch (err) { setError(err.message); setData(null); } finally { setLoading(false); // End loading no matter success/failure } }; fetchData(); }, []); if (loading) return <div>Loading...</div>; if (error) return <div>Oops: {error}</div>; return <div>{JSON.stringify(data)}</div>; }
3. WebView Redirect or Cache Issues (If Using WebView)
If your Android app uses a WebView to load a page with fetch, the problem might be API responses triggering redirects, or cache causing repeated page reloads. Try these fixes:
- Disable WebView cache in native Android code:
// Android Kotlin/Java example webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
- Check if your API response includes a
Locationheader that's redirecting the page, or if your fetch usesmode: 'no-cors'(this can cause unexpected behavior).
4. Cross-Origin Resource Sharing (CORS) Problems
Android WebView allows cross-origin requests by default, but if your API server isn't configured with the right CORS headers, fetch requests can fail silently—leaving your page stuck loading. To debug this:
- Open Chrome on your computer and go to
chrome://inspect - Find your app's WebView instance and click "Inspect"
- Check the Network tab to see if the fetch request is failing with a CORS error
If it's a CORS issue, ask your API team to add these headers to responses:
Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, OPTIONS
5. Infinite Loop from Mismanaged State Updates
If your fetch callback triggers a state update that causes the component to re-render, and that re-render runs the fetch again, you'll get a loop. Double-check your state logic to make sure you're only updating state when necessary—avoid unnecessary re-renders from redundant state changes.
内容的提问来源于stack exchange,提问作者Sassy

