Gagne, who tied the game at 3 with a deflection of Derian Hatcher's shot with 4:55 left in regulation, scored the winner from the right side of the net by redirecting Mike Knuble's shot.
Jeff Carter and Mike Richards also scored for the Flyers, who had not won at home since Nov. 24 when they beat Columbus in former Flyers coach Ken Hitchcock's debut with the Blue Jackets.
Philadelphia has won an NHL-low four home games this season (4-15-7).
Lee Stempniak, Keith Tkachuk, and David Backes scored for the Blues.
Backes redirected a centring pass from Radek Dvorak to break a 2-2 tie at 6:33 of the third period with his second goal of the season.
Philadelphia goaltender Michael Leighton, making his first NHL start since March 23, 2004, when he was with Chicago, stopped 25 shots. He was claimed on waivers from Nashville on Jan. 11.
Curtis Sanford made 22 saves for the Blues.
Each team scored twice in the second period. With St. Louis skating with a two-man advantage, Stempniak put the Blues ahead at 1:45 of the period by poking in a rebound of Dennis Wideman's shot.
Carter pulled the Flyers even at 5:13 with a snap shot from the right circle that sailed high over Sanford's outstretched glove.
Richards made it 2-1 at 9:53 when he hammered in a rebound of his own shot.
Tkachuk tied it again with 2:54 left in the period when he banked a shot off the left skate of Flyers defenceman Denis Gauthier.
Notes: St. Louis played its second of only four road games scheduled in February. ... The Blues are 4-2 against Eastern Conference teams this season. ... Carter grazed the post during a power play late in the first period. ... The Flyers have won eight of nine against the Blues. ... It was Backes' first goal in 21 games.