# sqlalchemy.orm.exc.DetachedInstanceError: 实例 <User at 0x...> 未绑定到任何会话

- **ID:** `python/sqlalchemy-detached-instance-error`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

尝试访问或修改一个已与会话分离的ORM实例，通常是在调用 session.close() 或 session.expunge_all() 之后。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Use session.merge() to reattach the instance** (95% 成功率)
   ```
   merged_user = session.merge(detached_user)
print(merged_user.name)
   ```
2. **Refresh the instance with session.refresh() after reattaching** (85% 成功率)
   ```
   session.add(detached_user)
session.refresh(detached_user)
   ```

## 无效尝试

- **Calling session.add() on the detached instance** — The instance is not in a pending state; it needs to be merged first. (80% 失败率)
- **Reopening the session and reusing the same instance** — The instance's state is stale; you need to merge or refresh it. (70% 失败率)
