
RuntimeError: Cannot add middleware after an application has started
快速结论:此报错在 Stable Diffusion WebUI 启动时出现,通常是因为 fastapi 版本过高(如 0.91+)与旧版 Starlette 或 WebUI 代码不兼容。优先将 fastapi 降级回 0.90.1。
问题场景
用户在 Windows 上启动 Stable Diffusion WebUI(Commit hash: ea9bd9fc),未使用特殊命令行参数,未安装 xformers,加载模型后 WebUI 提示正在运行,但随即报错退出。报错发生在 webui.py 第 232 行调用 app.add_middleware(GZipMiddleware) 时。
报错原文
File "C:\Users\tomwe\stable-diffusion-webui\webui.py", line 232, in webui
app.add_middleware(GZipMiddleware, minimum_size=1000)
File "C:\Users\tomwe\stable-diffusion-webui\venv\lib\site-packages\starlette\applications.py", line 135, in add_middleware
raise RuntimeError("Cannot add middleware after an application has started")
RuntimeError: Cannot add middleware after an application has started
原因分析
fastapi 的新版本(如 0.91.0 及以上)与当前 WebUI 代码依赖的 Starlette 内部行为不兼容,导致在应用启动后尝试添加中间件(GZipMiddleware)时抛出 RuntimeError。这是一个已知的依赖版本冲突问题,并非代码本身 bug。
环境排查
- Python 版本:3.10.6(或 Python 3.10.x)
- fastapi 版本:确认是否为 0.91.0 或更高版本
- Starlette 版本:间接受影响,但不需直接操作
- 操作系统:Windows(常见,但也可能在其他平台出现)
- WebUI 版本:Commit hash
ea9bd9fc或类似的较新提交
解决步骤
- 打开终端(cmd 或 PowerShell),使用
cd命令进入你的 Stable Diffusion WebUI 根目录(例如cd C:\stable-diffusion-webui)。 - 激活 Python 虚拟环境:
.\venv\Scripts\Activate.bat - 将
fastapi降级到0.90.1:pip install --upgrade fastapi==0.90.1注意:有的用户直接用
.\venv\Scripts\python.exe -m pip install --upgrade fastapi==0.90.1也能生效,这一步可能因权限问题需用管理员权限终端。 - 退出虚拟环境(可选):
deactivate - 关闭当前终端,重新运行
webui-user.bat(注意:不要直接运行webui.bat,否则环境变量可能设置不正确)。
可优先尝试:如果问题依然存在,检查是否配置了正确的 Python 路径。有用户反映忘记在 webui_user.bat 中设置 Python 路径(应指向 venv 中的 python.exe)也会导致类似问题。
验证方法
重新启动 Stable Diffusion WebUI 后,如果控制台输出 Running on local URL: http://127.0.0.1:7860 且不再出现 Traceback 报错,则表示问题已解决。



