React Native里fetch请求总是超时怎么办?

Dev · 诗雯 阅读 4

我在用React Native做App,调用公司内网API时经常遇到fetch请求超时的问题,明明网络是通的,浏览器能正常访问接口。

试过加timeout参数但好像没用,也检查了AndroidManifest.xml里的网络权限,都配好了。代码大概这样:

fetch('http://192.168.1.100:8080/api/data', {
  method: 'GET',
  timeout: 5000,
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error('请求失败:', err));

但还是经常卡住然后报Network request failed,这到底该怎么解决?

我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
雨萱 ☘︎
兄弟,fetch 原生根本不支持 timeout 参数,你写那属性是给谁看呢... 得自己包一层 Promise.race。不过我看你报 Network request failed,大概率不是超时,是 Android 9.0 以上默认禁止明文 HTTP 流量导致的。

先给你个能用的超时封装代码:

function fetchWithTimeout(url, options, timeout = 10000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), timeout)
)
]);
}

// 用法
fetchWithTimeout('http://192.168.1.100:8080/api/data', {
method: 'GET',
}, 5000)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));


然后解决 Android 拦截 HTTP 的问题,这才是重点。在 android/app/src/main/res/xml 目录下新建一个 network_security_config.xml 文件(没有 xml 文件夹就自己建一个):




192.168.1.100
localhost




最后在 AndroidManifest.xmlapplication 标签里加上这个配置引用:


    android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme"
android:networkSecurityConfig="@xml/network_security_config">


iOS 的话记得改 Info.plist 里的 NSAppTransportSecurity 允许 Arbitrary Loads。改完重新跑一下 npx react-native run-android 应该就好了。
点赞
2026-03-02 15:01