Why can a @MainActor view model still freeze UI or race?
Question
This SwiftUI feed model stutters badly on a 60 Hz screen (16.7 ms frame budget) every time a page loads:
@Observable @MainActor
final class FeedModel {
var posts: [Post] = []
var isLoading = false
func loadNextPage() async {
guard !isLoading else { return }
isLoading = true
let raw = try? await api.fetchPageBytes() // 4 MB JSON
posts += decodePosts(raw) // 85 ms CPU
isLoading = false
}
}A teammate calls Task.detached { await model.loadNextPage() }, which still freezes scrolling. Next, they remove @MainActor so Task.detached updates UI state off-main, triggering data races and Main Thread Checker warnings. Moving isLoading = true after await also duplicates pages on a double-tap.
- Why did
@MainActorfreeze scrolling, why did wrapping inTask.detachedstill stall, and why is removing@MainActorunsafe? - How do you offload the
85 msdecode while preventing actor reentrancy races?
Show hints (3)
- "WHERE SYNCHRONOUS WORK RUNS"
Calling a
@MainActormethod fromTask.detachedhops right back onto the main thread, wheredecodePosts(raw)still runs synchronously. - "ACTORS YIELD AT AWAIT"
Swift actors are reentrant. While suspended at
await, another tap or tab switch can enter@MainActorand mutateFeedModel. - "OFFLOAD AND GUARD DEFER"
Decode in a
nonisolated asynchelper returningSendablevalues. SetisLoading = truebeforeawait, and guard both the write anddeferwithfeedGeneration.
Show checked explanation
@MainActor runs the 85 ms synchronous decode on the main thread, dropping five 60 Hz frames. Wrapping the call in Task.detached still hops back into @MainActor, while removing @MainActor lets background code mutate UI state unsafely. Offload decoding to a nonisolated async helper, and guard both the write and defer with feedGeneration.
Frame-budget stalls at 60 Hz and 120 Hz, Swift 6 isolation vs Main Thread Checker confinement, and actor reentrancy across await (including conditional defer) were checked in a Python 3.12 actor model against Swift 6.0 and iOS 18 documentation. Checked by an editor other than the author.
Walkthrough
@MainActor guarantees single-threaded UI safety, not speed or atomicity across await. When api.fetchPageBytes() finishes, loadNextPage() hops back to @MainActor and runs the 85 ms decodePosts(raw) synchronously on the main thread. At 60 Hz (16.7 ms per frame), an 85 ms stall drops 5 full frames.
Why both Task.detached workarounds fail: Calling Task.detached { await model.loadNextPage() } still enters a @MainActor-isolated method, so execution hops right back onto the main thread and keeps freezing. Trying to write self.posts directly inside Task.detached on a @MainActor class is a Swift 6 compile-time isolation error. Removing @MainActor to silence the compiler lets background threads mutate UIKit views or ObservableObject / @Observable UI state, causing data races and runtime Main Thread Checker warnings.
| step | where it runs | time on main thread |
|---|---|---|
guard !isLoading; isLoading = true | @MainActor | < 1 ms |
await api.fetchPageBytes() | network / background | 0 ms |
await decodeOffMain(raw) | global concurrent pool | 0 ms |
posts += page; isLoading = false | @MainActor | < 1 ms |
In Swift 6.0, a nonisolated async helper runs on the global concurrent executor, moving the 85 ms parse of the 4 MB JSON off the main thread and returning Sendable [Post] values.
Guarding actor reentrancy: Swift actors yield at every await. Flip isLoading = true before the first await, and check token == feedGeneration both before appending posts and inside defer. An unconditional defer { isLoading = false } lets a stale waking task clear a newer feed's active spinner.
func loadNextPage() async {
guard !isLoading else { return }
let token = feedGeneration
isLoading = true
defer { if token == feedGeneration { isLoading = false } }
guard let raw = try? await api.fetchPageBytes() else { return }
let page = await Self.decodeOffMain(raw)
guard token == feedGeneration else { return }
posts += page
}
nonisolated static func decodeOffMain(_ data: Data) async -> [Post] {
(try? JSONDecoder().decode([Post].self, from: data)) ?? []
}Common mistakes
- Marking parsers, image decoders, or storage helpers
@MainActor, blocking the main thread and dropping frames during scrolling. - Wrapping a
@MainActorcall inTask.detachedexpecting background decoding, or removing@MainActorso background tasks mutate UIKit orObservableObjectstate. - Assuming
@MainActormakes an entireasyncfunction atomic. Anyawaityields the main actor and lets other events mutate state. - Using unconditional
defer { isLoading = false }or omitting cleanup. A waking stale task can clear a newer feed's loading spinner.
Follow-up questions
- "On a 120 Hz ProMotion display, how many frames does an 85 ms main-thread decode miss?" At
120 Hz, each frame budget is8.33 ms. An85 msmain-thread stall misses10full frame deadlines (crossing into the 11th frame), causing visible scroll hitches even when network fetches are async. - "How can actor reentrancy still corrupt the feed when isLoading is set before await?" Switching from Following to Trending bumps
feedGenerationand starts a new load withisLoading = true. Guard both the post append anddeferwithtoken == feedGeneration, so the stale task neither mixes feeds nor clears Trending's spinner. - "Why must Post conform to Sendable when decoding off the main actor in Swift 6?" Swift 6 enforces isolation boundaries at compile time. Making
Postan immutableSendablestruct proves the background executor cannot share mutable state with@MainActorafter returning the decoded array.
What a strong answer covers
Explains why @MainActor stalls even under Task.detached, and contrasts Swift 6 compile-time isolation with runtime Main Thread Checker warnings. Offloads decoding via nonisolated async with Sendable values, and guards writes plus defer with feedGeneration.
Open in interactive practice deck →