# 后台任务异常：AttributeError: 'NoneType' 对象没有属性 'send_email'

- **ID:** `python/fastapi-background-task-exception`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

BackgroundTasks 函数引用了请求作用域的依赖（数据库会话、current_user），而这些依赖在响应返回后即被关闭。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 0.100+ | active | — | — |
| 0.110+ | active | — | — |

## 解决方案

1. **** (92% 成功率)
   ```
   def send(uid: int):
    with SessionLocal() as s:
        user = s.get(User, uid)
        ...
background_tasks.add_task(send, user.id)  # pass IDs, not objects
   ```
2. **** (88% 成功率)
   ```
   Use a task queue (Celery/RQ) for long-running or dependency-heavy work.
   ```

## 无效尝试

- **** — Silences the error but the task never runs correctly. (70% 失败率)
- **** — Blocks the response; defeats the purpose of background tasks. (80% 失败率)
