Skip to content

[Due for payment 2026-11-19] [$175] [Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled #106338

Open

Description

@mountiny

(Vit's agent)

Problem

Sentry issue APP-NAP is an unhandled TypeError: undefined is not a function thrown inside react-native-pdf while a PDF download is canceled. It was found in the #quality-monitoring Sentry triage of Nov 6. No GitHub issue tracked it.

Evidence

  • First seen: Oct 21, 2026. Still active on Nov 9.
  • Impact: 649 events from 304 users in total. 411 events from 199 users in the last 7 days.
  • Mechanism: onunhandledrejection, so the error escapes as an unhandled promise rejection.
  • Stack (sample event, iOS HybridApp, release 9.5.26, view TransactionReceipt): node_modules/react-native-pdf/index.js:224 calls this.lastRNBFTask.cancel(...), reached from _downloadFile (line 179) and _prepareFile (line 161).
  • User-visible effect: not confirmed. The PDF may fail to render on the receipt screen.

What to check

  1. Which platforms and releases are affected (split the Sentry issue by os.name and release).
  2. Why lastRNBFTask.cancel is not a function at that point, and whether it happens when the user leaves the receipt before the download ends.
  3. Whether the cancel can be guarded, or the rejection caught, in our PDF view wrapper.

Expected

Canceling a PDF download never throws, and the receipt screen shows the PDF or a clear error.

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @suneox

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Nov 9, 2026
  2. self-assigned this
    on Nov 9, 2026
  3. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Nov 9, 2026
  4. melvin-bot commented on Nov 9, 2026

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @suneox (External)

  5. changed the title [-][Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled[/-] [+][$175] [Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled[/+] on Nov 9, 2026
  6. melvin-bot commented on Nov 9, 2026

    @melvin-bot
  7. MelvinBot commented on Nov 9, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    react-native-pdf loses the download task’s cancellation method, then calls it during a subsequent download. This explains both the TypeError and the unhandled rejection.

    Confidence: medium overall. The defect is verified in the dependency versions pinned by the 9.5.26 release source; the precise trigger in the reported production events remains unconfirmed.

    Code evidence and failure sequence
    1. The 9.5.26 release dependencies pin react-native-pdf 7.0.2 and react-native-blob-util 0.24.9.
    2. Blob-util attaches cancel() to its original download promise (fetch.js:337–348).
    3. PDF stores the result of .fetch(...).progress(...).catch(...). That final .catch() returns a different promise without cancel() (index.js:264–284).
    4. Another overlapping download calls lastRNBFTask.cancel() unconditionally (index.js:253–259).
    5. _downloadFile is asynchronous, but _prepareFile does not await its result. Its synchronous try/catch therefore misses the rejection (index.js:192–248).

    A changed source URI while the first download is pending is a supported route into this failure. Leaving the screen is not established as the trigger: unmount cancellation is commented out in this version (index.js:125–188). A network failure is not required.

    What changes do you think we should make in order to solve the problem?

    Add an App-owned dependency patch that:

    • Retains the original cancellable task separately from its promise handlers.
    • Safely coordinates cancellation and replacement loading.
    • Handles intentional cancellation without reporting a PDF-load failure.
    • Prevents stale callbacks from clearing or replacing the current download.
    • Observes asynchronous preparation failures and forwards genuine errors to onError.

    A typeof cancel guard alone would suppress this exception without restoring cancellation. Wrapper-side error handling alone cannot catch the currently detached rejection.

    Regression coverage and remaining verification

    Test the actual dependency JavaScript with mocked downloads/filesystem:

    • Keep download A pending, then switch to uncached URI B.
    • Verify A is cancelled, B starts exactly once, and no unhandled rejection occurs.
    • Verify stale completions cannot overwrite B or clear its task.
    • Verify intentional cancellation does not display the error fallback.
    • Verify genuine failures reach onError; preserve cache-hit and unmount behavior.

    The existing native PDF tests mock out the dependency, so they cannot detect this defect.

    No runtime reproduction was performed. Web testing cannot validate this path because web uses a different PDF renderer.

    Live Sentry data was unavailable. The OS/release breakdown, exact source-map correspondence, triggering sequence, and user-visible effect remain unverified; the issue’s event counts were not independently rechecked.


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106338) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.


    view run

  8. HindsightWise commented on Nov 9, 2026

    @HindsightWise

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    On native (iOS / Android, including TransactionReceipt), when a PDF receipt's source URI updates while an initial PDF download is still in flight, react-native-pdf throws an unhandled Promise rejection (TypeError: undefined is not a function at this.lastRNBFTask.cancel(...) in node_modules/react-native-pdf/index.js:224), recorded in Sentry as APP-NAP (onunhandledrejection).

    What is the root cause of that problem?

    There are two interacting root causes—one in our AttachmentModalBaseContent / AttachmentView state synchronization on TransactionReceipt that triggers back-to-back PDF loads with two different URIs, and one inside react-native-pdf's _downloadFile / _prepareFile implementation:

    1. Why TransactionReceipt triggers two consecutive PDF loads (componentDidMount followed immediately by componentDidUpdate with a different uri):

      • In src/pages/media/AttachmentModalScreen/AttachmentModalBaseContent/index.tsx:93-103, source and isAuthTokenRequiredState are mirrored into local state via useEffect, but sourceForAttachmentView = source || sourceProp falls back to sourceProp immediately on the render where sourceProp first becomes non-empty:
        const [source, setSource] = useState<AvatarSource>(() => sourceProp);
        const isLocalSource = typeof source === 'string' && /^file:|^blob:/.test(source);
        const sourceForAttachmentView = source || sourceProp;
        useEffect(() => {
            setSource(() => sourceProp);
        }, [sourceProp]);
        
        const [isAuthTokenRequiredState, setIsAuthTokenRequiredState] = useState(isAuthTokenRequired);
        useEffect(() => {
            setIsAuthTokenRequiredState(isAuthTokenRequired);
        }, [isAuthTokenRequired]);
      • When TransactionReceiptModalContent transitions from a loading/local state (isLocalFile: true -> isAuthTokenRequired: false when isFetchingWaypointsFromServer or a local draft resolves to a remote receipt URL) or when session.encryptedAuthToken hydrates/rotates in src/components/Attachments/AttachmentView/index.tsx:143,277:
        const encryptedSourceUrl = isAuthTokenRequired ? addEncryptedAuthTokenToURL(source as string, encryptedAuthToken) : (source as string);
        PDFView first mounts <PDF source={{uri: sourceURL, cache: true, expiration: 864000}} /> with the initial URI (either without encryptedAuthToken while isAuthTokenRequiredState lags by one render, or with an empty ?encryptedAuthToken= before session.encryptedAuthToken is populated), and on the very next render updates source.uri to the authenticated URL while the first download is still in flight.
    2. Why react-native-pdf throws an unhandled TypeError: undefined is not a function when source.uri updates mid-download:

      • In node_modules/react-native-pdf/index.js (_downloadFile, lines 264–284 of source / line 224 compiled):
        this.lastRNBFTask = ReactNativeBlobUtil.config({
            path: tempCacheFile,
            trusty: this.props.trustAllCerts,
        })
            .fetch(
                source.method ? source.method : 'GET',
                source.uri,
                source.headers ? source.headers : {},
                source.body ? source.body : ""
            )
            .progress((received, total) => {
                this.props.onLoadProgress && this.props.onLoadProgress(received / total);
                if (this._mounted) {
                    this.setState({progress: received / total});
                }
            })
            .catch(async (error) => {
                this._onError(error);
            });
        ReactNativeBlobUtil.config(...).fetch(...).progress(...) returns a StatefulPromise that exposes .cancel(). However, chaining .catch(...) at the end returns a standard native Promise (where .cancel is undefined) and assigns that standard Promise to this.lastRNBFTask.
      • When source.uri changes on the next render, componentDidUpdate (line 132) checks if (this.lastRNBFTask && this.lastRNBFTask.cancel). Because this.lastRNBFTask.cancel is undefined, that condition evaluates to false, skipping cancellation and falling into the else branch (this._loadFromSource(this.props.source) -> _prepareFile -> _downloadFile) with this.lastRNBFTask still non-null.
      • At the start of _downloadFile (line 255), if (this.lastRNBFTask) calls this.lastRNBFTask.cancel(...) without checking .cancel, throwing TypeError: undefined is not a function.
      • Because _prepareFile (async (source) => { try { ... this._downloadFile(source, cacheFile); } catch (e) { ... } }, line 209) calls this._downloadFile without await, the rejected Promise from async _downloadFile bypasses _prepareFile's try / catch and escapes globally as onunhandledrejection.

    What changes do you think we should make in order to solve the problem?

    1. Prevent premature/split-render PDF downloads in src/components/Attachments/AttachmentView/index.tsx and src/pages/media/AttachmentModalScreen/AttachmentModalBaseContent/index.tsx:

      • In AttachmentModalBaseContent/index.tsx, synchronize source and isAuthTokenRequiredState during render (or derive isAuthTokenRequiredForAttachmentView = source ? isAuthTokenRequiredState : isAuthTokenRequired) so sourceForAttachmentView and isAuthTokenRequired never lag by one render when sourceProp transitions from empty/local to remote.
      • In AttachmentView/index.tsx, if isAuthTokenRequired is true and !encryptedAuthToken, render the loading state (DefaultAttachmentView with shouldShowLoadingSpinnerIcon) rather than mounting <AttachmentViewPdf> with an unauthenticated URL that immediately changes on the next render.
    2. Fix this.lastRNBFTask cancellation and promise handling in react-native-pdf via a new numbered patch patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch (and update patches/react-native-pdf/details.md):

      • Store the ReactNativeBlobUtil StatefulPromise (from .fetch(...).progress(...)) on this.lastRNBFTask before attaching .then(...) / .catch(...) so this.lastRNBFTask.cancel remains a valid function.
      • Guard typeof this.lastRNBFTask?.cancel === 'function' in componentDidUpdate, componentWillUnmount, and _downloadFile, and track a local const task = ... reference so stale completion callbacks from a canceled task do not clobber a newer this.lastRNBFTask or invoke _onError after intentional cancellation.
      • await this._downloadFile(source, cacheFile) inside _prepareFile so any unexpected error is caught by _prepareFile's try / catch and routed to this._onError(e) instead of escaping as an unhandled rejection.

    What alternative solutions did you explore? (Optional)

    • Only patching react-native-pdf without fixing the two-render URI flip in AttachmentModalBaseContent / AttachmentView: Preventing the crash in react-native-pdf is necessary, but leaving the one-render isAuthTokenRequiredState lag in AttachmentModalBaseContent still causes TransactionReceipt to kick off and immediately abort an unauthenticated HTTP download on initial open. Fixing both eliminates the wasted network request and makes react-native-pdf cancellation safe under all URI updates.

    — submitted with Antigravity on the contributor's behalf

  9. staszekscp commented on Nov 9, 2026

    @staszekscp
    Contributor

    Hey @mountiny ! I'm looking at the issue

  10. kevinjosh10 commented on Nov 9, 2026

    @kevinjosh10

    Proposal

    What is the root cause of that problem?

    The crash is driven by an upstream promise-chaining defect in react-native-pdf combined with a double-render URI hydration cycle in Expensify's attachment viewers:

    1. Promise-chaining strips .cancel from this.lastRNBFTask in react-native-pdf

    In node_modules/react-native-pdf/index.js (_downloadFile, line 264–284 source / line 224 compiled):

    this.lastRNBFTask = ReactNativeBlobUtil.config({
        path: tempCacheFile,
        trusty: this.props.trustAllCerts,
    })
        .fetch(
            source.method ? source.method : 'GET',
            source.uri,
            source.headers ? source.headers : {},
            source.body ? source.body : ''
        )
        .progress((received, total) => {
            this.props.onLoadProgress && this.props.onLoadProgress(received / total);
            if (this._mounted) {
                this.setState({progress: received / total});
            }
        })
        .catch(async (error) => {
            this._onError(error);
        });
    • ReactNativeBlobUtil.config(...).fetch(...).progress(...) returns a StatefulPromise object, which provides the custom .cancel() method.
    • However, appending .catch(...) to the chain returns a standard native ECMAScript Promise, where .cancel is undefined.
    • Because this chained standard Promise is assigned to this.lastRNBFTask, this.lastRNBFTask.cancel is undefined.

    2. Unsafe invocation and unhandled rejection escape

    • At the start of _downloadFile (when loading a new source while a task exists):
      if (this.lastRNBFTask) {
          this.lastRNBFTask.cancel(() => {});
      }
      Because this.lastRNBFTask.cancel is undefined, calling this.lastRNBFTask.cancel(...) throws:
      TypeError: undefined is not a function (or this.lastRNBFTask.cancel is not a function).
    • In _prepareFile:
      async (source) => {
          try {
              ...
              this._downloadFile(source, cacheFile);
          } catch (error) {
              this._onError(error);
          }
      }
      this._downloadFile is an async method, but it is called without await. The rejected Promise thrown by _downloadFile escapes the synchronous try/catch block in _prepareFile and is emitted globally as an unhandled promise rejection (onunhandledrejection).

    3. Client trigger: Double-render URI hydration in AttachmentModalBaseContent

    In src/pages/media/AttachmentModalScreen/AttachmentModalBaseContent/index.tsx:93-103 and src/components/Attachments/AttachmentView/index.tsx:277:
    When a receipt modal opens, sourceProp updates, but isAuthTokenRequiredState lags by one render cycle before synchronizing in useEffect.
    As a result, AttachmentViewPdf mounts first with an unauthenticated URL, and immediately on the subsequent render receives the authenticated URL with ?encryptedAuthToken=. This rapid successive URI change triggers componentDidUpdate and _downloadFile while the first download is still active, hitting the exact cancellation defect above.


    What changes do you think we should make in order to solve the problem?

    1. Patch react-native-pdf with patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch

    In node_modules/react-native-pdf/index.js:

    1. Preserve the StatefulPromise reference before chaining callbacks:
      -    this.lastRNBFTask = ReactNativeBlobUtil.config({
      +    const task = ReactNativeBlobUtil.config({
               path: tempCacheFile,
               trusty: this.props.trustAllCerts,
           })
               .fetch(
                   source.method ? source.method : 'GET',
                   source.uri,
                   source.headers ? source.headers : {},
                   source.body ? source.body : ''
               )
               .progress((received, total) => {
                   this.props.onLoadProgress && this.props.onLoadProgress(received / total);
                   if (this._mounted) {
                       this.setState({progress: received / total});
                   }
               });
      +    this.lastRNBFTask = task;
      +    task.catch(async (error) => {
      +        if (this.lastRNBFTask === task) {
      +            this.lastRNBFTask = null;
      +        }
      +        this._onError(error);
      +    });
    2. Defensively guard all cancellation call sites (_downloadFile, componentDidUpdate, componentWillUnmount):
      -    if (this.lastRNBFTask) {
      -        this.lastRNBFTask.cancel(() => {});
      +    if (this.lastRNBFTask && typeof this.lastRNBFTask.cancel === 'function') {
      +        this.lastRNBFTask.cancel(() => {});
      +        this.lastRNBFTask = null;
           }
    3. In _prepareFile, await the call to this._downloadFile:
      -    this._downloadFile(source, cacheFile);
      +    await this._downloadFile(source, cacheFile);
      This guarantees that any error thrown during download preparation is trapped by the try/catch block and safely reported via this._onError.
    4. Document the patch in patches/react-native-pdf/details.md.

    2. Prevent premature split-render download in AttachmentModalBaseContent

    In src/pages/media/AttachmentModalScreen/AttachmentModalBaseContent/index.tsx:
    Derive isAuthTokenRequired directly during render rather than syncing asynchronously via useEffect:

    const isAuthTokenRequiredState = isAuthTokenRequired;

    And in AttachmentView/index.tsx:
    If isAuthTokenRequired is true and encryptedAuthToken has not yet loaded, render the loading placeholder instead of initiating an unauthenticated HTTP request.


    What alternative solutions did you explore? (Optional)

    • Only catching unhandled rejections globally in setupSentry.ts: Masking the unhandled rejection in Sentry telemetry leaves the user with a broken, blank PDF screen on native. Patching react-native-pdf ensures downloads cancel cleanly and subsequent downloads complete successfully.
    • Using PDFView without local task tracking: Without setting this.lastRNBFTask = null on cancel, stale callbacks from the aborted task could overwrite subsequent successful downloads. Local task reference tracking provides full isolation.

    What automated tests can you add to prevent this from re-occurring?

    1. In tests/unit/patches/ReactNativePdfPatchTest.ts (or a simulated download controller test):
      • Assert that invoking cancellation on an active download task successfully calls cancel() without throwing TypeError.
      • Assert that rapidly changing source.uri cancels the previous task and awaits the new task cleanly without unhandled promise rejections.
    2. In tests/ui/AttachmentViewPdfTest.tsx:
      • Verify that when source transitions from draft to remote authenticated URL, AttachmentView renders smoothly without throwing.

    Contributor details

    Your Expensify account email: lkevinjosh10@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

  11. added
    ReviewingHas a PR in review
    and removed on Nov 9, 2026
  12. TassioSales commented on Nov 9, 2026

    @TassioSales

    Contributor details
    Your Expensify account email: tassiolucian.ljs@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~0179cdc82689f205c7

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    Sentry issue APP-NAP records an unhandled TypeError: undefined is not a function thrown inside react-native-pdf when an in-progress PDF download is canceled or the viewer unmounts.

    What is the root cause of that problem?

    When PdfView unmounts while a download is active, the cancellation teardown invokes this.downloadTask.cancel(). In react-native-pdf, if the task has already settled or its cancellation callback is not defined, attempting to invoke the unassigned handler throws an unhandled TypeError.

    What changes do you think we should make in order to solve the problem?

    1. In src/components/PDFView/index.tsx (or patch for react-native-pdf), guard the cancellation cleanup in componentWillUnmount / useEffect cleanup:
      if (downloadTask && typeof downloadTask.cancel === 'function') {
          try {
              downloadTask.cancel();
          } catch (e) {
              // Ignore expected cancellation teardown error
          }
      }
    2. Ensure onError callback in PDFView safely filters out cancellation errors (CANCELLED / Download canceled) to prevent reporting benign aborts to Sentry.

    What alternative solutions did you explore? (Optional)

    • Preventing users from navigating away until PDF finishes: Rejected because users must be free to navigate or close modals at any time without blocking UI.

    What automated tests can you add to prevent this from re-occurring?

    In tests/unit/PDFViewTest.ts:

    • Add a unit test verifying that unmounting the PDF component while download is pending cleanly aborts without throwing unhandled exceptions.
  13. melvin-bot commented on Nov 9, 2026

    @melvin-bot

    ✅ Contributor details stored successfully. Thank you for contributing to Expensify!

  14. changed the title [-][$175] [Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled[/-] [+][Due for payment 2026-11-19] [$175] [Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled[/+] on Nov 12, 2026
  15. melvin-bot commented on Nov 12, 2026

    @melvin-bot

    @suneox

    The solution for this issue has been 🚀 deployed to production 🚀 in version 9.5.36-0 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:

    If no regressions arise, payment will be issued on 2026-11-19. 🎊

    The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the Contributor+ Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributorOverdue

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions