python
runtime_error
ai_generated
true
运行时错误:依赖项 'get_db' 返回的值不是有效的依赖项
RuntimeError: Dependency 'get_db' returned a value that is not a valid dependency
ID: python/fastapi-dependency-cache-error
80%修复率
83%置信度
0证据数
2025-09-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
根因分析
FastAPI 依赖注入函数返回了非可调用的对象
English
FastAPI 依赖注入函数返回了非可调用的对象
解决方案
-
95% 成功率 确保依赖函数返回可调用对象或正确类型
def get_db(): return SessionLocal() # 返回实例而非类 -
90% 成功率 使用类作为依赖并正确配置
class CommonQueryParams: def __init__(self, q: str = None): self.q = q @app.get('/items') def get_items(params: CommonQueryParams = Depends()): ...
无效尝试
常见但无效的做法:
-
在依赖函数中返回 None
80% 失败
None 不是有效依赖
-
使用类作为依赖但不实例化
70% 失败
FastAPI 需要可调用对象