download

Why can a @MainActor view model still freeze UI or race?

Mobile~10 minReviewed 2 Dec 2026Free · No sign-in

Question

This SwiftUI feed model stutters badly on a 60 Hz screen (16.7 ms frame budget) every time a page loads:

"SWIFT"
@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.

  1. Why did @MainActor freeze scrolling, why did wrapping in Task.detached still stall, and why is removing @MainActor unsafe?
  2. How do you offload the 85 ms decode while preventing actor reentrancy races?
Show hints (3)
  1. "WHERE SYNCHRONOUS WORK RUNS"

    Calling a @MainActor method from Task.detached hops right back onto the main thread, where decodePosts(raw) still runs synchronously.

  2. "ACTORS YIELD AT AWAIT"

    Swift actors are reentrant. While suspended at await, another tap or tab switch can enter @MainActor and mutate FeedModel.

  3. "OFFLOAD AND GUARD DEFER"

    Decode in a nonisolated async helper returning Sendable values. Set isLoading = true before await, and guard both the write and defer with feedGeneration.

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.

stepwhere it runstime on main thread
guard !isLoading; isLoading = true@MainActor< 1 ms
await api.fetchPageBytes()network / background0 ms
await decodeOffMain(raw)global concurrent pool0 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.

"SWIFT"
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 @MainActor call in Task.detached expecting background decoding, or removing @MainActor so background tasks mutate UIKit or ObservableObject state.
  • Assuming @MainActor makes an entire async function atomic. Any await yields 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 is 8.33 ms. An 85 ms main-thread stall misses 10 full 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 feedGeneration and starts a new load with isLoading = true. Guard both the post append and defer with token == 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 Post an immutable Sendable struct proves the background executor cannot share mutable state with @MainActor after 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 →

Original OfferVibe question. Swift MainActor · The Swift Programming Language: Concurrency · Diagnosing memory, thread, and crash issues early · Swift Observation.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.