You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Alamofire publisher返回explicitlyCancelled错误如何解决?

错误原因

Combine 框架中,sink 方法返回的 AnyCancellable 订阅对象需要被持有才能维持订阅生命周期。你当前代码没有存储这个订阅对象,load 方法执行结束后临时生成的 AnyCancellable 会被立即释放,系统会自动取消对应的未完成网络请求,所以就出现了 explicitlyCancelled 错误。
你之前用 .response 方法没有问题,是因为Alamofire内部自动持有了回调的上下文,不需要开发者手动维护生命周期。

修复方案
  1. 导入Combine框架,使用其提供的Cancellable存储能力
  2. 在视图中声明用于存储订阅对象的集合
  3. 将sink返回的订阅对象存入集合,避免提前释放

修复后完整代码

import SwiftUI
import Alamofire
import Combine // 新增导入

struct ContentView: View {
    // 新增订阅存储集合
    @State private var cancellables = Set<AnyCancellable>()
    
    var body: some View {
        Text("Hello, world!")
            .padding()
            .onAppear(perform: load)
    }
    
    struct TestResponse: Decodable {
        let userId: Int
        let id: Int
        let title: String
        let body: String
    }
    
    func load(){
        AF.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil)
            .validate()
            .publishDecodable(type: [TestResponse].self)
            .print()
            .sink { print($0) }
            .store(in: &cancellables) // 新增:持有订阅对象
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

修改后再次运行即可正常收到网络请求返回的结果。

内容的提问来源于stack exchange,提问作者Geoffrey Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:06:04