Fetch/Axios在React Native中严重崩溃(但仅适用于某些URL) [英] Fetch / Axios crashing hard in React Native (but only for certain URLs)

查看:256
本文介绍了Fetch/Axios在React Native中严重崩溃(但仅适用于某些URL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行某些 API调用时,我的应用程序崩溃严重,我将其范围缩小到了这一点:

  • 这不是HTTP vs HTTPS的事情
  • 我最终使用了两种不同的模拟API,但令我惊讶的是,一种有效,而另一种无效.两者基本相同,请参见下面的代码段
  • 在WIFI或蜂窝网络上的行为相同
  • 与axios中的问题相同,而不是获取
  • 调用catch块时出现非描述性的网络错误,但随后应用仍然难以崩溃

环境:Android 10(实际设备),RN 0.61.5

下面的两个调用都只是执行一个简单的HTTP GET,导致返回JSON代码段.一种有效,另一种导致严重崩溃.

async foo() {
    try {

        // this endpoint CRASHES my app
        const r = await fetch("http://jsonplaceholder.typicode.com/todos/1");
        
        // this endpoint works just fine
        //const r = await fetch("http://echo.jsontest.com/key/value/one/two");

    } catch(e) {
        console.log("Invoked, but the app still crashes hard right after");
    }
}

解决方案

好吧,我在Logcat中发现了一个提示-看来使用OkHttp3会引起某种形式的版本冲突,这种冲突仅表现在其中一个响应中(可能是由于CORS标头,但这纯粹是毫无根据的猜测;).

我的解决方法是从

api(platform("com.squareup.okhttp3:okhttp-bom:4.7.2"))
api("com.squareup.okhttp3:okhttp")
api("com.squareup.okhttp3:logging-interceptor")

更改对build.gradle中OkHttp3的依赖

implementation "com.squareup.okhttp3:okhttp:4.7.2"

api(platform("com.squareup.okhttp3:okhttp-bom:4.7.2"))
api("com.squareup.okhttp3:okhttp")
api("com.squareup.okhttp3:logging-interceptor")

My app is crashing hard when doing certain API calls, and I narrowed it down to this point:

  • it's not an HTTP vs HTTPS thing
  • I eventually used two different mock APIs, and to my suprise, one worked, the other didn't. Both are basically the same, see snippet below
  • same behavior on both WIFI or cellular network
  • same issue in axios instead of fetch
  • the catch block is invoked with a nondescript network error, but then the app still crashes hard

Environment: Android 10 (actual device), RN 0.61.5

Both calls below just do a simple HTTP GET which results in a JSON snippet being returned. One works, the other causes a hard crash.

async foo() {
    try {

        // this endpoint CRASHES my app
        const r = await fetch("http://jsonplaceholder.typicode.com/todos/1");
        
        // this endpoint works just fine
        //const r = await fetch("http://echo.jsontest.com/key/value/one/two");

    } catch(e) {
        console.log("Invoked, but the app still crashes hard right after");
    }
}

解决方案

Ok, I found a hint in Logcat - it appears that using OkHttp3 is causing some sort of versioning conflict that only manifests in one of the responses (maybe due to CORS headers, but that's pure, unfounded speculation ;).

My fix was to change my dependency on OkHttp3 in build.gradle from

implementation "com.squareup.okhttp3:okhttp:4.7.2"

to

api(platform("com.squareup.okhttp3:okhttp-bom:4.7.2"))
api("com.squareup.okhttp3:okhttp")
api("com.squareup.okhttp3:logging-interceptor")

这篇关于Fetch/Axios在React Native中严重崩溃(但仅适用于某些URL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆