Skip to content

Unable to cancel effects when the view is dismissed at the exact moment #3663

@dazy1030

Description

@dazy1030

Description

If you close a screen that was pushed with navigationDestination at just the right moment, the next effect continues to run. The code below demonstrates the issue. You can reproduce it by tapping the navigation bar’s back button or calling dismiss while the fetch1 action is still being processed.

enum Action {
  case onAppear
  case fetchResult1
  case fetchResult2
}

var body: some ReducerOf<Self> {
  Reduce { state, action in
    switch action {
    case .onAppear:
      return .run { send in
        @Dependency(\.continuousClock) var clock
        try await clock.sleep(for: .seconds(1))
        await send(.fetchResult1)
      }
    case .fetchResult1:
      // press back button
      // or
      // Task {
      //   @Dependency(\.dismiss) var dismiss
      //   await dismiss()
      // }
      return .run { send in
        @Dependency(\.continuousClock) var clock
        try await clock.sleep(for: .seconds(1))
        await send(.fetchResult2)
      }
    case .fetchResult2:
      return .none
    }
  }
}

Checklist

  • I have determined whether this bug is also reproducible in a vanilla SwiftUI project.
  • If possible, I've reproduced the issue using the main branch of this package.
  • This issue hasn't been addressed in an existing GitHub issue or discussion.

Expected behavior

Do not run the effect emitted by fetchResult1, or cancel it immediately after it starts.

Actual behavior

The effect is processed and fetchResult2 gets dispatched, which triggers a runtime warning from PresentationReducer’s reduce method.

Reproducing project

https://github.com/dazy1030/AppPlayground/tree/tca/dismiss-cancel

The Composable Architecture version information

1.18.0, 1.19.1, main(abd1331)

Destination operating system

iOS 18.1

Xcode version information

Version 16.2 (16C5032a)

Swift Compiler version information

swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1)
Target: arm64-apple-macosx15.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working due to a bug in the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions