引言
在服务端确认前显示改动使界面即便网络快也显得慢,因为每个动作付一次往返。乐观更新立即把改动当作已成功应用,再与服务端实际响应对账或在失败时回滚。它是少量状态管理,使交互感觉即时,前提是回滚与对账路径被处理,因为持续存在的错误乐观更新比慢的更糟。
什么是乐观更新
乐观更新预测结果:用户把待办标记完成时,UI 在服务端确认前立即标记它完成。请求在后台发出,UI 已在预期状态。若服务端同意则不再发生什么;若不同意或失败,UI 回滚或应用服务端版本。
好处是感知延迟:交互因不等网络而感觉即时。风险是用户看到并据以行动的错误预测,因此对账与回滚必须健壮且可见。
捕获先前状态
回滚需要更新前的状态,因此在应用预测改动前捕获快照。把快照与待处理请求放在一起,使回滚精确恢复用户之前所见,而非部分更新的状态。
对列表,只捕获受影响项及其位置而非整个列表,使回滚是定向改动。对值,捕获先前值。请求在途时快照必须不可变,因为可能有其他更新同时被应用。
与服务端响应对账
成功时服务端可返回与预测不同的结果:服务端分配的 id、计算值、时间戳。通过用服务端响应替换乐观值来对账,使 UI 收敛到真相。若预测对,对账是空操作。
对账不得覆盖更新的更新。若对同一项有两个更新在途,按序应用并各对其自己的响应对账,使较早的对账不覆盖较晚的乐观改动。按项跟踪请求 id 或序列号让你按序应用响应。
失败时回滚
失败时回滚到捕获的先前状态并告诉用户。静默回滚——改动消失而无解释——令人困惑;可见的错误加重试是诚实的。理想情况下回滚平滑,使项返回其位而非闪一下。
重试策略要紧:有些失败是暂时的,重试可无需打扰用户而成功;其他(校验错误)是永久的,需要回滚与消息。区分它们,使网络抖动不浮现错误,而被拒绝的请求则浮现。
并发与多更新
可同时有多个乐观更新在途,对不同的项或同一项。对不同的项,它们独立、各在自身失败时回滚。对同一项,它们需要顺序:按项排队更新,或版本化使较晚的回滚不撤销较早的成功改动。
常见 bug 是回滚到因其间另一次更新成功而过期的快照。按操作捕获先前状态并只回滚该操作的改动,而非把整个项还原到旧值。这就是按操作快照要紧的原因。
乐观何处显现
乐观更新适合成功率高且结果快而可预测的动作:切换点赞、标记已读、重排列表、加评论。它们不适合结果依赖客户端无法预测的服务端逻辑之处(库存检查、价格计算)或错误结果代价高之处。
对客户端无法做的预测,另一模式合适:显示待处理状态(项上的 spinner)而非预测结果,使用户看到动作进行中而无错误猜测。在预测可靠处选乐观;不可靠处用待处理状态。
常见陷阱与小结
不要静默回滚;告诉用户。不要把整个项回滚到过期快照、撤销其间的成功。不要乱序应用响应、覆盖更新的更新。也不要在客户端无法预测结果处用乐观,否则你显示用户据以行动的错误状态。
乐观更新通过在服务端确认前应用预测改动、再对账或回滚,使界面感觉即时。按操作捕获先前状态、按序与服务端响应对账、失败时可见回滚、并把乐观保留给可预测的高成功率动作。于是交互快而无错误状态持续。
代码示例
# optimistic flow
user acts -> apply the predicted change NOW (UI updates instantly)
-> send the request in the background
-> success: reconcile with the server response (usually no-op)
-> failure: roll back to the previous state, tell the user
# perception: instant; risk: a wrong prediction shown and acted on
interface PendingOp<T> { id: string; previous: T; next: T; }
function applyOptimistic<T extends { id: string }>(state: T[], op: PendingOp<T>): T[] {
const snapshot = state.find((x) => x.id === op.id);
// the snapshot (previous) is kept with the op for rollback
return state.map((x) => (x.id === op.id ? op.next : x));
}
function rollback<T extends { id: string }>(state: T[], op: PendingOp<T>): T[] {
return state.map((x) => (x.id === op.id ? op.previous : x)); // restore exactly
}
# on success
server response replaces the optimistic value (id, computed fields, version)
# ordering: two updates to the same item
apply them in order; reconcile each against its OWN response
# an out-of-order response must not clobber a newer optimistic change
# per-item request id / sequence lets you apply responses in order
async function runOptimistic<T extends { id: string }>(
state: T[], op: PendingOp<T>, send: (next: T) => Promise<T>,
): Promise<T[]> {
const next = applyOptimistic(state, op); // instant UI
try {
const server = await send(op.next); // background request
return state.map((x) => (x.id === op.id ? server : x)); // reconcile
} catch (err) {
showError('Could not save; reverted'); // visible, not silent
return rollback(state, op); // restore previous exactly
}
}
# concurrency
different items: independent; each rolls back its own change
same item: order the updates (queue per item) or version them
# do NOT roll back the whole item to a stale snapshot: an in-between
# success would be undone. Roll back only this operation's change
# good for optimism (fast, predictable, high success)
toggle like, mark read, reorder, add comment
# use a pending state instead (spinner on the item)
inventory check, price/computed value, server-side validation result
# the client cannot predict => show "in progress", not a wrong guess