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: @mallenexpensify

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. 11 remaining items

  11. 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]

  12. expensify-chore-bot commented on Nov 17, 2026

    @expensify-chore-bot

    @suneox Eep! 4 days overdue now. Issues have feelings too...

  13. suneox commented on Nov 18, 2026

    @suneox
    Contributor

    Contributor+ Checklist:

    • [Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      N/A. The bug is in react-native-pdf: since 6.7.7, _downloadFile stores the promise returned by .catch() in lastRNBFTask instead of the download task, so it has no cancel(). It reached the App with the 6.7.3 → 7.0.1 bump in [Pre RN 0.81] Bump react-native-pdf #72204. It only shows when the PDF source changes while it's still downloading, so it couldn't reasonably be caught in that review, and the fix is going upstream in fix(download): don't report a canceled or replaced download through onError wonday/react-native-pdf#1057.

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      N/A, not critical: an unhandled promise rejection, and in a rare race the previous receipt PDF was shown.

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

      I don't think a manual regression test is needed: it depends on the auth token changing while a PDF is still downloading, which QA can't time reliably. tests/unit/ReactNativePDFDownloadTest.tsx from Fix react-native-pdf throws undefined is not a function #106351 covers it.

  14. suneox commented on Nov 18, 2026

    @suneox
    Contributor

    APP-NAP is no longer happening after build 9.5.36-0, which includes #106351.

  15. expensify-chore-bot commented on Nov 18, 2026

    @expensify-chore-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  16. expensify-chore-bot commented on Nov 18, 2026

    @expensify-chore-bot

    Payment Summary

    Resolving PRs:

    BugZero Checklist (@mallenexpensify)

    • I have confirmed assignees, roles, and Upwork contracts look correct
    • I have paid out Upwork contracts / manual NewDot requests
    • [BugZero Assignee] I have created a GH issue for creating/updating the regression test once above steps have been agreed upon
  17. mallenexpensify commented on Nov 20, 2026

    @mallenexpensify
    Contributor

    Claude posting on behalf of Matt:

    Ready. Job price: $175 (standard, no Help Wanted, assigned 2026-11-09).

    • suneox (C+): 100%, via NewDot

    suneox confirms the Sentry error stopped after 9.5.36-0. No deploy blockers.

    Next: pay. No Caps+Y.

    Evidence
    • C+ checklist, no test steps: comment
    • PR 106351: by staszekscp (BEC and agency, no per-issue pay), merged 2026-11-10, production 2026-11-12, approved by mountiny. suneox posted the Reviewer Checklist.
    • Test videos: C+ 3/5.

    PAYPREP v1

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

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions