2024-06-06 uni.request设置timeout在真机环境下无效,h5和模拟器环境下生效
为什么,我其实并没有解决uni.request设置了timeout为3秒后在断网状态下依旧loading了20秒才捕获错误,也许是因为写法有什么问题吧,我自己新建了个小程序然后写了个请求:
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{ title }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
uni.showLoading({
title: '加载中'
});
uni.request({
url: "xxx",
method: "POST",
timeout: 100,
data: {},
header: {},
success() {
uni.showModal({
title: '加载成功'
});
},
fail() {
uni.showModal({
title: '加载失败'
});
},
complete() {
uni.hideLoading();
}
})
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
这个例子在小程序真机测试上是能成功在3秒内捕获错误的,我最后是怎么解决的呢?
需求就是要在无网络情况下不要uni.showloading那么就,3秒就够,那么如果我能直接获取网络状态岂不是连uni.request都不用触发了?
是的,我在请求接口前先判断有无网络:
uni.getNetworkType({ success: function (res) { console.log('网络状态', res.networkType); if (res.networkType === 'none') { // 没有网络 uni.showToast({ title: '当前无网络', icon: 'none' }); uni.hideLoading() } } });
在判断无网的时候直接reject一个错误码回去,间接完成了需求。

浙公网安备 33010602011771号