The veteran senator remained tight-lipped about his intentions before he reached the Senate floor early on Friday morning on a night of high suspense. He told reporters to "watch the show" as he entered the room.
His vote to reject the bill drew gasps in the chamber and applause from Democratic senators.
His defiance was a hammer blow to a key election promise of a US President who has long been an adversary of Mr McCain.
In 2015, Mr Trump said the Vietnam veteran - who spent five-and-a-half years in a notorious Hanoi prison - was "not a war hero".
"He was a war hero because he was captured? I like people who weren’t captured," said the billionaire businessman.
Conversely, Mr McCain has been a thorn in the President's side since he entered the White House, describing his administration as "in disarray" in February and later likening Mr Trump's attacks on the press to the behaviour of a dictator.
The President adopted a more conciliatory tone ahead of Friday's crucial vote, tweeting: "So great that John McCain is coming back to vote."
But after seeing his bill defeated, he said Mr McCain and two other Republican senators had "let the American people down" by joining 48 Democrats in rejecting his proposals.
Mr McCain said he voted against repealing Obamacare because the bill "offered no replacement to actually reform our health care system and deliver affordable, quality health care to our citizens".
The Republication amendment, which was defeated 51 votes to 49, would have repealed a mandate that most individuals get health insurance and suspended a requirement that large companies provide coverage to their employees.
Republicans Lisa Murkowski of Alaska and Susan Collins of Maine also voted against it.