Fix undo race conditions

CID 18096, 18115, 18116, 18137