React应用本地视频无法使用:加载后服务器崩溃报错
React本地视频背景导致服务器崩溃问题
我在React项目里用本地视频做背景,视频加载完成后服务器直接挂了,报下面的错误。试过两个不同的播放器库,也试过原生HTML video标签,结果都一样。video标签语法没问题,换成YouTube链接就能正常运行。
throw er; // Unhandled 'error' event ^ TypeError: Cannot set property closed of #<Readable> which has only a getter at FsReadStream.close (C:x\node_modules\memfs\lib\volume.js:2047:17) at FsReadStream._destroy (C:\x\node_modules\memfs\lib\volume.js:2032:10) at _destroy (node:internal/streams/destroy:109:10) at class_1.destroy (node:internal/streams/destroy:71:5) at class_1.<anonymous> (C:\x\node_modules\memfs\lib\volume.js:1962:22) at class_1.emit (node:events:539:35) at endReadableNT (node:internal/streams/readable:1344:12) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) Emitted 'error' event on class_1 instance at: at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
问题根源
错误栈指向memfs库的FsReadStream.close方法,这个库是内存文件系统,推测是本地视频文件的读取流程和memfs的实现冲突了——React开发环境可能用了依赖memfs的工具(比如某些webpack插件、mock库),读取本地视频流时触发了memfs的bug,它试图修改Node.js Readable流只读的closed属性。
解决方法
把视频文件放到公开目录
确保视频文件放在React项目的public文件夹下,用绝对路径引用:<video autoPlay loop muted playsInline> <source src="/background.mp4" type="video/mp4" /> </video>这样开发服务器会直接静态托管文件,绕过可能的memfs拦截。
排除memfs对视频文件的处理
如果你的项目里有用到依赖memfs的工具(比如react-app-rewired、自定义webpack配置),在配置里把视频文件后缀(.mp4/.webm等)排除在memfs的处理范围外,让它们走原生文件系统读取。临时替换memfs版本
这个bug在memfs的某些版本存在,试试降级到3.4.10或者升级到最新稳定版:npm install memfs@3.4.10 --save-dev用CDN托管视频
暂时把视频传到免费CDN(比如自己搭的或者公开存储),用远程链接引用,避开本地文件读取的问题,和你用YouTube链接能正常运行的逻辑一致。
内容的提问来源于stack exchange,提问作者Lucian Plamadeala
相关产品推荐
相关产品推荐

