Skip to content

事务隔离级别:脏读或幻读

快速摘要

你的事务隔离级别太低 —— 并发事务可以读取未提交数据或看到幻影行。

为什么发生

  • Read Uncommitted 隔离允许脏读,其他事务的未提交更改可见

  • Read Committed 隔离允许同一事务内的不可重复读和幻影行

  • 默认隔离级别对于操作的一致性要求来说太低

最小示例

✗ 错误代码
// Default isolation (Read Committed) — non-repeatable read
const tx = await db.beginTransaction();
const balance1 = await tx.query('SELECT balance FROM accounts WHERE id = 1');
// Another transaction commits a change to balance here
const balance2 = await tx.query('SELECT balance FROM accounts WHERE id = 1');
// balance1 !== balance2 — non-repeatable read!
✓ 修复代码
const tx = await db.beginTransaction();
await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
const balance1 = await tx.query('SELECT balance FROM accounts WHERE id = 1');
// Same transaction — balance cannot change
const balance2 = await tx.query('SELECT balance FROM accounts WHERE id = 1');
// balance1 === balance2 — repeatable read guaranteed

将隔离级别设置为 Repeatable Read 确保同一事务内的读取始终返回相同数据,防止不可重复读。

如何诊断

  • 用 SHOW TRANSACTION ISOLATION LEVEL 检查当前隔离级别

  • 查看一致性要求 —— 事务是否需要可重复读或可串行化?

  • 用并发事务测试以检测脏读、不可重复读或幻读

如何修复

  • 将隔离级别设置为 Repeatable Read 或 Serializable 以获得更强一致性保证

  • 使用 SELECT FOR UPDATE 锁定事务期间不得更改的行

  • 如果悲观锁定代价太高,使用带版本号的乐观并发控制

如何预防

  • 根据每个事务的一致性要求选择隔离级别

  • 测试并发事务场景以验证隔离级别防止异常

相关资源

相关术语

相关课程

← 返回语言