Expo React Native FileSystem下载暂停恢复报错(no download object)求助
问题分析
你遇到的「no download object」错误核心原因是:每次调用downloadFile时都会重新创建一个新的DownloadResumable实例,而暂停/恢复操作需要复用同一个实例才能生效。当前代码里downloadResumable是函数内部的局部变量,状态切换(比如从start到pause)时,新的实例没有关联之前的下载任务,自然找不到对应的下载对象。
解决方案
需要把DownloadResumable实例保存到组件状态中,确保暂停/恢复操作复用同一个实例。具体修改步骤如下:
1. 新增状态保存下载实例
在现有状态定义中添加:
const [downloadResumable, setDownloadResumable] = useState(null);
2. 修改downloadFile函数逻辑
调整函数内部逻辑,仅在**开始下载(start)**时创建实例并保存到状态,暂停/恢复时直接使用状态中已有的实例:
// 下载功能实现 const downloadFile = async (endpoint, name) => { switch (downloadStatus) { case "start": // 仅在开始下载时创建实例并保存 var ext = endpoint.substr(endpoint.lastIndexOf('.') + 1); const newDownloadResumable = FileSystem.createDownloadResumable( endpoint, FileSystem.documentDirectory + name + "." + ext, {}, callback ); setDownloadResumable(newDownloadResumable); setIsDownloading(true); try { const { uri } = await newDownloadResumable.downloadAsync(); saveFile(uri); setIsDownloading(false); setDownloadResumable(null); // 下载完成后清理实例 } catch (e) { console.error(e); setIsDownloading(false); setDownloadResumable(null); // 错误时清理实例 } break; case "pause": if (!downloadResumable) return; // 无实例时直接返回 try { await downloadResumable.pauseAsync(); setIsDownloading(false); } catch (e) { console.error(e); } break; case "resume": if (!downloadResumable) return; // 无实例时直接返回 setIsDownloading(true); try { const { uri } = await downloadResumable.resumeAsync(); saveFile(uri); setIsDownloading(false); setDownloadResumable(null); // 恢复完成后清理实例 } catch (e) { console.error(e); setIsDownloading(false); } break; default: break; } };
3. 关键改动说明
- 将
downloadResumable从局部变量改为组件状态,确保跨函数调用时能复用同一个下载实例 - 暂停/恢复前先检查实例是否存在,避免无意义的错误
- 下载完成或出错后清理实例,防止内存泄漏
4. 额外优化建议
- 添加重复下载的判断:如果
isDownloading为true,禁止再次触发start操作 - 处理组件卸载时的下载任务:在
useEffect的清理函数中暂停并清理实例,避免内存泄漏:
useEffect(() => { return () => { if (downloadResumable) { downloadResumable.pauseAsync().catch(e => console.error(e)); } }; }, [downloadResumable]);
内容的提问来源于stack exchange,提问作者Mahdi
相关产品推荐
相关产品推荐

